PackageManagerService.java revision dbaef6dc62507b0e0623e76882e31e68413d469d
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.DELETE_PACKAGES;
20import static android.Manifest.permission.INSTALL_PACKAGES;
21import static android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS;
22import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
23import static android.Manifest.permission.REQUEST_DELETE_PACKAGES;
24import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
25import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
27import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
28import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
29import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
30import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
31import static android.content.pm.PackageManager.DELETE_KEEP_DATA;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
33import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
34import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
35import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
36import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
37import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
38import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
39import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
40import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
41import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
42import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
43import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
44import static android.content.pm.PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID;
45import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
46import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
47import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
48import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
49import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
50import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
51import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
52import static android.content.pm.PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE;
53import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
54import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
55import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
56import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
57import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
58import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
59import static android.content.pm.PackageManager.INSTALL_INTERNAL;
60import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
62import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
63import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
64import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
65import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
66import static android.content.pm.PackageManager.MATCH_ALL;
67import static android.content.pm.PackageManager.MATCH_ANY_USER;
68import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
69import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
70import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
71import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
72import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
73import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES;
74import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
75import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
76import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL;
77import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
78import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
79import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
80import static android.content.pm.PackageManager.MOVE_FAILED_LOCKED_USER;
81import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
82import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
83import static android.content.pm.PackageManager.PERMISSION_DENIED;
84import static android.content.pm.PackageManager.PERMISSION_GRANTED;
85import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
86import static android.content.pm.PackageParser.isApkFile;
87import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
88import static android.system.OsConstants.O_CREAT;
89import static android.system.OsConstants.O_RDWR;
90
91import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
92import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
93import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
94import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
95import static com.android.internal.util.ArrayUtils.appendInt;
96import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
97import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
98import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
99import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
100import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
101import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
102import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter;
103import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
104import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
105import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
106
107import static dalvik.system.DexFile.getNonProfileGuidedCompilerFilter;
108
109import android.Manifest;
110import android.annotation.IntDef;
111import android.annotation.NonNull;
112import android.annotation.Nullable;
113import android.app.ActivityManager;
114import android.app.AppOpsManager;
115import android.app.IActivityManager;
116import android.app.ResourcesManager;
117import android.app.admin.IDevicePolicyManager;
118import android.app.admin.SecurityLog;
119import android.app.backup.IBackupManager;
120import android.content.BroadcastReceiver;
121import android.content.ComponentName;
122import android.content.ContentResolver;
123import android.content.Context;
124import android.content.IIntentReceiver;
125import android.content.Intent;
126import android.content.IntentFilter;
127import android.content.IntentSender;
128import android.content.IntentSender.SendIntentException;
129import android.content.ServiceConnection;
130import android.content.pm.ActivityInfo;
131import android.content.pm.ApplicationInfo;
132import android.content.pm.AppsQueryHelper;
133import android.content.pm.AuxiliaryResolveInfo;
134import android.content.pm.ChangedPackages;
135import android.content.pm.ComponentInfo;
136import android.content.pm.FallbackCategoryProvider;
137import android.content.pm.FeatureInfo;
138import android.content.pm.IDexModuleRegisterCallback;
139import android.content.pm.IOnPermissionsChangeListener;
140import android.content.pm.IPackageDataObserver;
141import android.content.pm.IPackageDeleteObserver;
142import android.content.pm.IPackageDeleteObserver2;
143import android.content.pm.IPackageInstallObserver2;
144import android.content.pm.IPackageInstaller;
145import android.content.pm.IPackageManager;
146import android.content.pm.IPackageMoveObserver;
147import android.content.pm.IPackageStatsObserver;
148import android.content.pm.InstantAppInfo;
149import android.content.pm.InstantAppRequest;
150import android.content.pm.InstantAppResolveInfo;
151import android.content.pm.InstrumentationInfo;
152import android.content.pm.IntentFilterVerificationInfo;
153import android.content.pm.KeySet;
154import android.content.pm.PackageCleanItem;
155import android.content.pm.PackageInfo;
156import android.content.pm.PackageInfoLite;
157import android.content.pm.PackageInstaller;
158import android.content.pm.PackageManager;
159import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
160import android.content.pm.PackageManagerInternal;
161import android.content.pm.PackageParser;
162import android.content.pm.PackageParser.ActivityIntentInfo;
163import android.content.pm.PackageParser.PackageLite;
164import android.content.pm.PackageParser.PackageParserException;
165import android.content.pm.PackageStats;
166import android.content.pm.PackageUserState;
167import android.content.pm.ParceledListSlice;
168import android.content.pm.PermissionGroupInfo;
169import android.content.pm.PermissionInfo;
170import android.content.pm.ProviderInfo;
171import android.content.pm.ResolveInfo;
172import android.content.pm.ServiceInfo;
173import android.content.pm.SharedLibraryInfo;
174import android.content.pm.Signature;
175import android.content.pm.UserInfo;
176import android.content.pm.VerifierDeviceIdentity;
177import android.content.pm.VerifierInfo;
178import android.content.pm.VersionedPackage;
179import android.content.res.Resources;
180import android.database.ContentObserver;
181import android.graphics.Bitmap;
182import android.hardware.display.DisplayManager;
183import android.net.Uri;
184import android.os.Binder;
185import android.os.Build;
186import android.os.Bundle;
187import android.os.Debug;
188import android.os.Environment;
189import android.os.Environment.UserEnvironment;
190import android.os.FileUtils;
191import android.os.Handler;
192import android.os.IBinder;
193import android.os.Looper;
194import android.os.Message;
195import android.os.Parcel;
196import android.os.ParcelFileDescriptor;
197import android.os.PatternMatcher;
198import android.os.Process;
199import android.os.RemoteCallbackList;
200import android.os.RemoteException;
201import android.os.ResultReceiver;
202import android.os.SELinux;
203import android.os.ServiceManager;
204import android.os.ShellCallback;
205import android.os.SystemClock;
206import android.os.SystemProperties;
207import android.os.Trace;
208import android.os.UserHandle;
209import android.os.UserManager;
210import android.os.UserManagerInternal;
211import android.os.storage.IStorageManager;
212import android.os.storage.StorageEventListener;
213import android.os.storage.StorageManager;
214import android.os.storage.StorageManagerInternal;
215import android.os.storage.VolumeInfo;
216import android.os.storage.VolumeRecord;
217import android.provider.Settings.Global;
218import android.provider.Settings.Secure;
219import android.security.KeyStore;
220import android.security.SystemKeyStore;
221import android.service.pm.PackageServiceDumpProto;
222import android.system.ErrnoException;
223import android.system.Os;
224import android.text.TextUtils;
225import android.text.format.DateUtils;
226import android.util.ArrayMap;
227import android.util.ArraySet;
228import android.util.Base64;
229import android.util.BootTimingsTraceLog;
230import android.util.DisplayMetrics;
231import android.util.EventLog;
232import android.util.ExceptionUtils;
233import android.util.Log;
234import android.util.LogPrinter;
235import android.util.MathUtils;
236import android.util.PackageUtils;
237import android.util.Pair;
238import android.util.PrintStreamPrinter;
239import android.util.Slog;
240import android.util.SparseArray;
241import android.util.SparseBooleanArray;
242import android.util.SparseIntArray;
243import android.util.Xml;
244import android.util.jar.StrictJarFile;
245import android.util.proto.ProtoOutputStream;
246import android.view.Display;
247
248import com.android.internal.R;
249import com.android.internal.annotations.GuardedBy;
250import com.android.internal.app.IMediaContainerService;
251import com.android.internal.app.ResolverActivity;
252import com.android.internal.content.NativeLibraryHelper;
253import com.android.internal.content.PackageHelper;
254import com.android.internal.logging.MetricsLogger;
255import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
256import com.android.internal.os.IParcelFileDescriptorFactory;
257import com.android.internal.os.RoSystemProperties;
258import com.android.internal.os.SomeArgs;
259import com.android.internal.os.Zygote;
260import com.android.internal.telephony.CarrierAppUtils;
261import com.android.internal.util.ArrayUtils;
262import com.android.internal.util.ConcurrentUtils;
263import com.android.internal.util.DumpUtils;
264import com.android.internal.util.FastPrintWriter;
265import com.android.internal.util.FastXmlSerializer;
266import com.android.internal.util.IndentingPrintWriter;
267import com.android.internal.util.Preconditions;
268import com.android.internal.util.XmlUtils;
269import com.android.server.AttributeCache;
270import com.android.server.DeviceIdleController;
271import com.android.server.EventLogTags;
272import com.android.server.FgThread;
273import com.android.server.IntentResolver;
274import com.android.server.LocalServices;
275import com.android.server.LockGuard;
276import com.android.server.ServiceThread;
277import com.android.server.SystemConfig;
278import com.android.server.SystemServerInitThreadPool;
279import com.android.server.Watchdog;
280import com.android.server.net.NetworkPolicyManagerInternal;
281import com.android.server.pm.Installer.InstallerException;
282import com.android.server.pm.PermissionsState.PermissionState;
283import com.android.server.pm.Settings.DatabaseVersion;
284import com.android.server.pm.Settings.VersionInfo;
285import com.android.server.pm.dex.DexManager;
286import com.android.server.pm.dex.DexoptOptions;
287import com.android.server.pm.dex.PackageDexUsage;
288import com.android.server.storage.DeviceStorageMonitorInternal;
289
290import dalvik.system.CloseGuard;
291import dalvik.system.DexFile;
292import dalvik.system.VMRuntime;
293
294import libcore.io.IoUtils;
295import libcore.util.EmptyArray;
296
297import org.xmlpull.v1.XmlPullParser;
298import org.xmlpull.v1.XmlPullParserException;
299import org.xmlpull.v1.XmlSerializer;
300
301import java.io.BufferedOutputStream;
302import java.io.BufferedReader;
303import java.io.ByteArrayInputStream;
304import java.io.ByteArrayOutputStream;
305import java.io.File;
306import java.io.FileDescriptor;
307import java.io.FileInputStream;
308import java.io.FileOutputStream;
309import java.io.FileReader;
310import java.io.FilenameFilter;
311import java.io.IOException;
312import java.io.PrintWriter;
313import java.lang.annotation.Retention;
314import java.lang.annotation.RetentionPolicy;
315import java.nio.charset.StandardCharsets;
316import java.security.DigestInputStream;
317import java.security.MessageDigest;
318import java.security.NoSuchAlgorithmException;
319import java.security.PublicKey;
320import java.security.SecureRandom;
321import java.security.cert.Certificate;
322import java.security.cert.CertificateEncodingException;
323import java.security.cert.CertificateException;
324import java.text.SimpleDateFormat;
325import java.util.ArrayList;
326import java.util.Arrays;
327import java.util.Collection;
328import java.util.Collections;
329import java.util.Comparator;
330import java.util.Date;
331import java.util.HashMap;
332import java.util.HashSet;
333import java.util.Iterator;
334import java.util.List;
335import java.util.Map;
336import java.util.Objects;
337import java.util.Set;
338import java.util.concurrent.CountDownLatch;
339import java.util.concurrent.Future;
340import java.util.concurrent.TimeUnit;
341import java.util.concurrent.atomic.AtomicBoolean;
342import java.util.concurrent.atomic.AtomicInteger;
343
344/**
345 * Keep track of all those APKs everywhere.
346 * <p>
347 * Internally there are two important locks:
348 * <ul>
349 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
350 * and other related state. It is a fine-grained lock that should only be held
351 * momentarily, as it's one of the most contended locks in the system.
352 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
353 * operations typically involve heavy lifting of application data on disk. Since
354 * {@code installd} is single-threaded, and it's operations can often be slow,
355 * this lock should never be acquired while already holding {@link #mPackages}.
356 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
357 * holding {@link #mInstallLock}.
358 * </ul>
359 * Many internal methods rely on the caller to hold the appropriate locks, and
360 * this contract is expressed through method name suffixes:
361 * <ul>
362 * <li>fooLI(): the caller must hold {@link #mInstallLock}
363 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
364 * being modified must be frozen
365 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
366 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
367 * </ul>
368 * <p>
369 * Because this class is very central to the platform's security; please run all
370 * CTS and unit tests whenever making modifications:
371 *
372 * <pre>
373 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
374 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
375 * </pre>
376 */
377public class PackageManagerService extends IPackageManager.Stub
378        implements PackageSender {
379    static final String TAG = "PackageManager";
380    static final boolean DEBUG_SETTINGS = false;
381    static final boolean DEBUG_PREFERRED = false;
382    static final boolean DEBUG_UPGRADE = false;
383    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
384    private static final boolean DEBUG_BACKUP = false;
385    private static final boolean DEBUG_INSTALL = false;
386    private static final boolean DEBUG_REMOVE = false;
387    private static final boolean DEBUG_BROADCASTS = false;
388    private static final boolean DEBUG_SHOW_INFO = false;
389    private static final boolean DEBUG_PACKAGE_INFO = false;
390    private static final boolean DEBUG_INTENT_MATCHING = false;
391    private static final boolean DEBUG_PACKAGE_SCANNING = false;
392    private static final boolean DEBUG_VERIFY = false;
393    private static final boolean DEBUG_FILTERS = false;
394    private static final boolean DEBUG_PERMISSIONS = false;
395    private static final boolean DEBUG_SHARED_LIBRARIES = false;
396
397    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
398    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
399    // user, but by default initialize to this.
400    public static final boolean DEBUG_DEXOPT = false;
401
402    private static final boolean DEBUG_ABI_SELECTION = false;
403    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
404    private static final boolean DEBUG_TRIAGED_MISSING = false;
405    private static final boolean DEBUG_APP_DATA = false;
406
407    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
408    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
409
410    private static final boolean HIDE_EPHEMERAL_APIS = false;
411
412    private static final boolean ENABLE_FREE_CACHE_V2 =
413            SystemProperties.getBoolean("fw.free_cache_v2", true);
414
415    private static final int RADIO_UID = Process.PHONE_UID;
416    private static final int LOG_UID = Process.LOG_UID;
417    private static final int NFC_UID = Process.NFC_UID;
418    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
419    private static final int SHELL_UID = Process.SHELL_UID;
420
421    // Cap the size of permission trees that 3rd party apps can define
422    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
423
424    // Suffix used during package installation when copying/moving
425    // package apks to install directory.
426    private static final String INSTALL_PACKAGE_SUFFIX = "-";
427
428    static final int SCAN_NO_DEX = 1<<1;
429    static final int SCAN_FORCE_DEX = 1<<2;
430    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
431    static final int SCAN_NEW_INSTALL = 1<<4;
432    static final int SCAN_UPDATE_TIME = 1<<5;
433    static final int SCAN_BOOTING = 1<<6;
434    static final int SCAN_TRUSTED_OVERLAY = 1<<7;
435    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8;
436    static final int SCAN_REPLACING = 1<<9;
437    static final int SCAN_REQUIRE_KNOWN = 1<<10;
438    static final int SCAN_MOVE = 1<<11;
439    static final int SCAN_INITIAL = 1<<12;
440    static final int SCAN_CHECK_ONLY = 1<<13;
441    static final int SCAN_DONT_KILL_APP = 1<<14;
442    static final int SCAN_IGNORE_FROZEN = 1<<15;
443    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16;
444    static final int SCAN_AS_INSTANT_APP = 1<<17;
445    static final int SCAN_AS_FULL_APP = 1<<18;
446    /** Should not be with the scan flags */
447    static final int FLAGS_REMOVE_CHATTY = 1<<31;
448
449    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
450
451    private static final int[] EMPTY_INT_ARRAY = new int[0];
452
453    private static final int TYPE_UNKNOWN = 0;
454    private static final int TYPE_ACTIVITY = 1;
455    private static final int TYPE_RECEIVER = 2;
456    private static final int TYPE_SERVICE = 3;
457    private static final int TYPE_PROVIDER = 4;
458    @IntDef(prefix = { "TYPE_" }, value = {
459            TYPE_UNKNOWN,
460            TYPE_ACTIVITY,
461            TYPE_RECEIVER,
462            TYPE_SERVICE,
463            TYPE_PROVIDER,
464    })
465    @Retention(RetentionPolicy.SOURCE)
466    public @interface ComponentType {}
467
468    /**
469     * Timeout (in milliseconds) after which the watchdog should declare that
470     * our handler thread is wedged.  The usual default for such things is one
471     * minute but we sometimes do very lengthy I/O operations on this thread,
472     * such as installing multi-gigabyte applications, so ours needs to be longer.
473     */
474    static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
475
476    /**
477     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
478     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
479     * settings entry if available, otherwise we use the hardcoded default.  If it's been
480     * more than this long since the last fstrim, we force one during the boot sequence.
481     *
482     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
483     * one gets run at the next available charging+idle time.  This final mandatory
484     * no-fstrim check kicks in only of the other scheduling criteria is never met.
485     */
486    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
487
488    /**
489     * Whether verification is enabled by default.
490     */
491    private static final boolean DEFAULT_VERIFY_ENABLE = true;
492
493    /**
494     * The default maximum time to wait for the verification agent to return in
495     * milliseconds.
496     */
497    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
498
499    /**
500     * The default response for package verification timeout.
501     *
502     * This can be either PackageManager.VERIFICATION_ALLOW or
503     * PackageManager.VERIFICATION_REJECT.
504     */
505    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
506
507    static final String PLATFORM_PACKAGE_NAME = "android";
508
509    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
510
511    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
512            DEFAULT_CONTAINER_PACKAGE,
513            "com.android.defcontainer.DefaultContainerService");
514
515    private static final String KILL_APP_REASON_GIDS_CHANGED =
516            "permission grant or revoke changed gids";
517
518    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
519            "permissions revoked";
520
521    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
522
523    private static final String PACKAGE_SCHEME = "package";
524
525    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
526
527    /** Permission grant: not grant the permission. */
528    private static final int GRANT_DENIED = 1;
529
530    /** Permission grant: grant the permission as an install permission. */
531    private static final int GRANT_INSTALL = 2;
532
533    /** Permission grant: grant the permission as a runtime one. */
534    private static final int GRANT_RUNTIME = 3;
535
536    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
537    private static final int GRANT_UPGRADE = 4;
538
539    /** Canonical intent used to identify what counts as a "web browser" app */
540    private static final Intent sBrowserIntent;
541    static {
542        sBrowserIntent = new Intent();
543        sBrowserIntent.setAction(Intent.ACTION_VIEW);
544        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
545        sBrowserIntent.setData(Uri.parse("http:"));
546    }
547
548    /**
549     * The set of all protected actions [i.e. those actions for which a high priority
550     * intent filter is disallowed].
551     */
552    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
553    static {
554        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
555        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
556        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
557        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
558    }
559
560    // Compilation reasons.
561    public static final int REASON_FIRST_BOOT = 0;
562    public static final int REASON_BOOT = 1;
563    public static final int REASON_INSTALL = 2;
564    public static final int REASON_BACKGROUND_DEXOPT = 3;
565    public static final int REASON_AB_OTA = 4;
566    public static final int REASON_INACTIVE_PACKAGE_DOWNGRADE = 5;
567
568    public static final int REASON_LAST = REASON_INACTIVE_PACKAGE_DOWNGRADE;
569
570    /** All dangerous permission names in the same order as the events in MetricsEvent */
571    private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList(
572            Manifest.permission.READ_CALENDAR,
573            Manifest.permission.WRITE_CALENDAR,
574            Manifest.permission.CAMERA,
575            Manifest.permission.READ_CONTACTS,
576            Manifest.permission.WRITE_CONTACTS,
577            Manifest.permission.GET_ACCOUNTS,
578            Manifest.permission.ACCESS_FINE_LOCATION,
579            Manifest.permission.ACCESS_COARSE_LOCATION,
580            Manifest.permission.RECORD_AUDIO,
581            Manifest.permission.READ_PHONE_STATE,
582            Manifest.permission.CALL_PHONE,
583            Manifest.permission.READ_CALL_LOG,
584            Manifest.permission.WRITE_CALL_LOG,
585            Manifest.permission.ADD_VOICEMAIL,
586            Manifest.permission.USE_SIP,
587            Manifest.permission.PROCESS_OUTGOING_CALLS,
588            Manifest.permission.READ_CELL_BROADCASTS,
589            Manifest.permission.BODY_SENSORS,
590            Manifest.permission.SEND_SMS,
591            Manifest.permission.RECEIVE_SMS,
592            Manifest.permission.READ_SMS,
593            Manifest.permission.RECEIVE_WAP_PUSH,
594            Manifest.permission.RECEIVE_MMS,
595            Manifest.permission.READ_EXTERNAL_STORAGE,
596            Manifest.permission.WRITE_EXTERNAL_STORAGE,
597            Manifest.permission.READ_PHONE_NUMBERS,
598            Manifest.permission.ANSWER_PHONE_CALLS);
599
600
601    /**
602     * Version number for the package parser cache. Increment this whenever the format or
603     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
604     */
605    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
606
607    /**
608     * Whether the package parser cache is enabled.
609     */
610    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
611
612    final ServiceThread mHandlerThread;
613
614    final PackageHandler mHandler;
615
616    private final ProcessLoggingHandler mProcessLoggingHandler;
617
618    /**
619     * Messages for {@link #mHandler} that need to wait for system ready before
620     * being dispatched.
621     */
622    private ArrayList<Message> mPostSystemReadyMessages;
623
624    final int mSdkVersion = Build.VERSION.SDK_INT;
625
626    final Context mContext;
627    final boolean mFactoryTest;
628    final boolean mOnlyCore;
629    final DisplayMetrics mMetrics;
630    final int mDefParseFlags;
631    final String[] mSeparateProcesses;
632    final boolean mIsUpgrade;
633    final boolean mIsPreNUpgrade;
634    final boolean mIsPreNMR1Upgrade;
635
636    // Have we told the Activity Manager to whitelist the default container service by uid yet?
637    @GuardedBy("mPackages")
638    boolean mDefaultContainerWhitelisted = false;
639
640    @GuardedBy("mPackages")
641    private boolean mDexOptDialogShown;
642
643    /** The location for ASEC container files on internal storage. */
644    final String mAsecInternalPath;
645
646    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
647    // LOCK HELD.  Can be called with mInstallLock held.
648    @GuardedBy("mInstallLock")
649    final Installer mInstaller;
650
651    /** Directory where installed third-party apps stored */
652    final File mAppInstallDir;
653
654    /**
655     * Directory to which applications installed internally have their
656     * 32 bit native libraries copied.
657     */
658    private File mAppLib32InstallDir;
659
660    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
661    // apps.
662    final File mDrmAppPrivateInstallDir;
663
664    // ----------------------------------------------------------------
665
666    // Lock for state used when installing and doing other long running
667    // operations.  Methods that must be called with this lock held have
668    // the suffix "LI".
669    final Object mInstallLock = new Object();
670
671    // ----------------------------------------------------------------
672
673    // Keys are String (package name), values are Package.  This also serves
674    // as the lock for the global state.  Methods that must be called with
675    // this lock held have the prefix "LP".
676    @GuardedBy("mPackages")
677    final ArrayMap<String, PackageParser.Package> mPackages =
678            new ArrayMap<String, PackageParser.Package>();
679
680    final ArrayMap<String, Set<String>> mKnownCodebase =
681            new ArrayMap<String, Set<String>>();
682
683    // Keys are isolated uids and values are the uid of the application
684    // that created the isolated proccess.
685    @GuardedBy("mPackages")
686    final SparseIntArray mIsolatedOwners = new SparseIntArray();
687
688    /**
689     * Tracks new system packages [received in an OTA] that we expect to
690     * find updated user-installed versions. Keys are package name, values
691     * are package location.
692     */
693    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
694    /**
695     * Tracks high priority intent filters for protected actions. During boot, certain
696     * filter actions are protected and should never be allowed to have a high priority
697     * intent filter for them. However, there is one, and only one exception -- the
698     * setup wizard. It must be able to define a high priority intent filter for these
699     * actions to ensure there are no escapes from the wizard. We need to delay processing
700     * of these during boot as we need to look at all of the system packages in order
701     * to know which component is the setup wizard.
702     */
703    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
704    /**
705     * Whether or not processing protected filters should be deferred.
706     */
707    private boolean mDeferProtectedFilters = true;
708
709    /**
710     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
711     */
712    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
713    /**
714     * Whether or not system app permissions should be promoted from install to runtime.
715     */
716    boolean mPromoteSystemApps;
717
718    @GuardedBy("mPackages")
719    final Settings mSettings;
720
721    /**
722     * Set of package names that are currently "frozen", which means active
723     * surgery is being done on the code/data for that package. The platform
724     * will refuse to launch frozen packages to avoid race conditions.
725     *
726     * @see PackageFreezer
727     */
728    @GuardedBy("mPackages")
729    final ArraySet<String> mFrozenPackages = new ArraySet<>();
730
731    final ProtectedPackages mProtectedPackages;
732
733    @GuardedBy("mLoadedVolumes")
734    final ArraySet<String> mLoadedVolumes = new ArraySet<>();
735
736    boolean mFirstBoot;
737
738    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
739
740    // System configuration read by SystemConfig.
741    final int[] mGlobalGids;
742    final SparseArray<ArraySet<String>> mSystemPermissions;
743    @GuardedBy("mAvailableFeatures")
744    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
745
746    // If mac_permissions.xml was found for seinfo labeling.
747    boolean mFoundPolicyFile;
748
749    private final InstantAppRegistry mInstantAppRegistry;
750
751    @GuardedBy("mPackages")
752    int mChangedPackagesSequenceNumber;
753    /**
754     * List of changed [installed, removed or updated] packages.
755     * mapping from user id -> sequence number -> package name
756     */
757    @GuardedBy("mPackages")
758    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
759    /**
760     * The sequence number of the last change to a package.
761     * mapping from user id -> package name -> sequence number
762     */
763    @GuardedBy("mPackages")
764    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
765
766    class PackageParserCallback implements PackageParser.Callback {
767        @Override public final boolean hasFeature(String feature) {
768            return PackageManagerService.this.hasSystemFeature(feature, 0);
769        }
770
771        final List<PackageParser.Package> getStaticOverlayPackagesLocked(
772                Collection<PackageParser.Package> allPackages, String targetPackageName) {
773            List<PackageParser.Package> overlayPackages = null;
774            for (PackageParser.Package p : allPackages) {
775                if (targetPackageName.equals(p.mOverlayTarget) && p.mIsStaticOverlay) {
776                    if (overlayPackages == null) {
777                        overlayPackages = new ArrayList<PackageParser.Package>();
778                    }
779                    overlayPackages.add(p);
780                }
781            }
782            if (overlayPackages != null) {
783                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
784                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
785                        return p1.mOverlayPriority - p2.mOverlayPriority;
786                    }
787                };
788                Collections.sort(overlayPackages, cmp);
789            }
790            return overlayPackages;
791        }
792
793        final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages,
794                String targetPackageName, String targetPath) {
795            if ("android".equals(targetPackageName)) {
796                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
797                // native AssetManager.
798                return null;
799            }
800            List<PackageParser.Package> overlayPackages =
801                    getStaticOverlayPackagesLocked(allPackages, targetPackageName);
802            if (overlayPackages == null || overlayPackages.isEmpty()) {
803                return null;
804            }
805            List<String> overlayPathList = null;
806            for (PackageParser.Package overlayPackage : overlayPackages) {
807                if (targetPath == null) {
808                    if (overlayPathList == null) {
809                        overlayPathList = new ArrayList<String>();
810                    }
811                    overlayPathList.add(overlayPackage.baseCodePath);
812                    continue;
813                }
814
815                try {
816                    // Creates idmaps for system to parse correctly the Android manifest of the
817                    // target package.
818                    //
819                    // OverlayManagerService will update each of them with a correct gid from its
820                    // target package app id.
821                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
822                            UserHandle.getSharedAppGid(
823                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
824                    if (overlayPathList == null) {
825                        overlayPathList = new ArrayList<String>();
826                    }
827                    overlayPathList.add(overlayPackage.baseCodePath);
828                } catch (InstallerException e) {
829                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
830                            overlayPackage.baseCodePath);
831                }
832            }
833            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
834        }
835
836        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
837            synchronized (mPackages) {
838                return getStaticOverlayPathsLocked(
839                        mPackages.values(), targetPackageName, targetPath);
840            }
841        }
842
843        @Override public final String[] getOverlayApks(String targetPackageName) {
844            return getStaticOverlayPaths(targetPackageName, null);
845        }
846
847        @Override public final String[] getOverlayPaths(String targetPackageName,
848                String targetPath) {
849            return getStaticOverlayPaths(targetPackageName, targetPath);
850        }
851    };
852
853    class ParallelPackageParserCallback extends PackageParserCallback {
854        List<PackageParser.Package> mOverlayPackages = null;
855
856        void findStaticOverlayPackages() {
857            synchronized (mPackages) {
858                for (PackageParser.Package p : mPackages.values()) {
859                    if (p.mIsStaticOverlay) {
860                        if (mOverlayPackages == null) {
861                            mOverlayPackages = new ArrayList<PackageParser.Package>();
862                        }
863                        mOverlayPackages.add(p);
864                    }
865                }
866            }
867        }
868
869        @Override
870        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
871            // We can trust mOverlayPackages without holding mPackages because package uninstall
872            // can't happen while running parallel parsing.
873            // Moreover holding mPackages on each parsing thread causes dead-lock.
874            return mOverlayPackages == null ? null :
875                    getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath);
876        }
877    }
878
879    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
880    final ParallelPackageParserCallback mParallelPackageParserCallback =
881            new ParallelPackageParserCallback();
882
883    public static final class SharedLibraryEntry {
884        public final @Nullable String path;
885        public final @Nullable String apk;
886        public final @NonNull SharedLibraryInfo info;
887
888        SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
889                String declaringPackageName, int declaringPackageVersionCode) {
890            path = _path;
891            apk = _apk;
892            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
893                    declaringPackageName, declaringPackageVersionCode), null);
894        }
895    }
896
897    // Currently known shared libraries.
898    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
899    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
900            new ArrayMap<>();
901
902    // All available activities, for your resolving pleasure.
903    final ActivityIntentResolver mActivities =
904            new ActivityIntentResolver();
905
906    // All available receivers, for your resolving pleasure.
907    final ActivityIntentResolver mReceivers =
908            new ActivityIntentResolver();
909
910    // All available services, for your resolving pleasure.
911    final ServiceIntentResolver mServices = new ServiceIntentResolver();
912
913    // All available providers, for your resolving pleasure.
914    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
915
916    // Mapping from provider base names (first directory in content URI codePath)
917    // to the provider information.
918    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
919            new ArrayMap<String, PackageParser.Provider>();
920
921    // Mapping from instrumentation class names to info about them.
922    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
923            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
924
925    // Mapping from permission names to info about them.
926    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
927            new ArrayMap<String, PackageParser.PermissionGroup>();
928
929    // Packages whose data we have transfered into another package, thus
930    // should no longer exist.
931    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
932
933    // Broadcast actions that are only available to the system.
934    @GuardedBy("mProtectedBroadcasts")
935    final ArraySet<String> mProtectedBroadcasts = new ArraySet<>();
936
937    /** List of packages waiting for verification. */
938    final SparseArray<PackageVerificationState> mPendingVerification
939            = new SparseArray<PackageVerificationState>();
940
941    /** Set of packages associated with each app op permission. */
942    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
943
944    final PackageInstallerService mInstallerService;
945
946    private final PackageDexOptimizer mPackageDexOptimizer;
947    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
948    // is used by other apps).
949    private final DexManager mDexManager;
950
951    private AtomicInteger mNextMoveId = new AtomicInteger();
952    private final MoveCallbacks mMoveCallbacks;
953
954    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
955
956    // Cache of users who need badging.
957    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
958
959    /** Token for keys in mPendingVerification. */
960    private int mPendingVerificationToken = 0;
961
962    volatile boolean mSystemReady;
963    volatile boolean mSafeMode;
964    volatile boolean mHasSystemUidErrors;
965    private volatile boolean mEphemeralAppsDisabled;
966
967    ApplicationInfo mAndroidApplication;
968    final ActivityInfo mResolveActivity = new ActivityInfo();
969    final ResolveInfo mResolveInfo = new ResolveInfo();
970    ComponentName mResolveComponentName;
971    PackageParser.Package mPlatformPackage;
972    ComponentName mCustomResolverComponentName;
973
974    boolean mResolverReplaced = false;
975
976    private final @Nullable ComponentName mIntentFilterVerifierComponent;
977    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
978
979    private int mIntentFilterVerificationToken = 0;
980
981    /** The service connection to the ephemeral resolver */
982    final EphemeralResolverConnection mInstantAppResolverConnection;
983    /** Component used to show resolver settings for Instant Apps */
984    final ComponentName mInstantAppResolverSettingsComponent;
985
986    /** Activity used to install instant applications */
987    ActivityInfo mInstantAppInstallerActivity;
988    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
989
990    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
991            = new SparseArray<IntentFilterVerificationState>();
992
993    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
994
995    // List of packages names to keep cached, even if they are uninstalled for all users
996    private List<String> mKeepUninstalledPackages;
997
998    private UserManagerInternal mUserManagerInternal;
999
1000    private DeviceIdleController.LocalService mDeviceIdleController;
1001
1002    private File mCacheDir;
1003
1004    private ArraySet<String> mPrivappPermissionsViolations;
1005
1006    private Future<?> mPrepareAppDataFuture;
1007
1008    private static class IFVerificationParams {
1009        PackageParser.Package pkg;
1010        boolean replacing;
1011        int userId;
1012        int verifierUid;
1013
1014        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1015                int _userId, int _verifierUid) {
1016            pkg = _pkg;
1017            replacing = _replacing;
1018            userId = _userId;
1019            replacing = _replacing;
1020            verifierUid = _verifierUid;
1021        }
1022    }
1023
1024    private interface IntentFilterVerifier<T extends IntentFilter> {
1025        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1026                                               T filter, String packageName);
1027        void startVerifications(int userId);
1028        void receiveVerificationResponse(int verificationId);
1029    }
1030
1031    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1032        private Context mContext;
1033        private ComponentName mIntentFilterVerifierComponent;
1034        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1035
1036        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1037            mContext = context;
1038            mIntentFilterVerifierComponent = verifierComponent;
1039        }
1040
1041        private String getDefaultScheme() {
1042            return IntentFilter.SCHEME_HTTPS;
1043        }
1044
1045        @Override
1046        public void startVerifications(int userId) {
1047            // Launch verifications requests
1048            int count = mCurrentIntentFilterVerifications.size();
1049            for (int n=0; n<count; n++) {
1050                int verificationId = mCurrentIntentFilterVerifications.get(n);
1051                final IntentFilterVerificationState ivs =
1052                        mIntentFilterVerificationStates.get(verificationId);
1053
1054                String packageName = ivs.getPackageName();
1055
1056                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1057                final int filterCount = filters.size();
1058                ArraySet<String> domainsSet = new ArraySet<>();
1059                for (int m=0; m<filterCount; m++) {
1060                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1061                    domainsSet.addAll(filter.getHostsList());
1062                }
1063                synchronized (mPackages) {
1064                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1065                            packageName, domainsSet) != null) {
1066                        scheduleWriteSettingsLocked();
1067                    }
1068                }
1069                sendVerificationRequest(verificationId, ivs);
1070            }
1071            mCurrentIntentFilterVerifications.clear();
1072        }
1073
1074        private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) {
1075            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1076            verificationIntent.putExtra(
1077                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1078                    verificationId);
1079            verificationIntent.putExtra(
1080                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1081                    getDefaultScheme());
1082            verificationIntent.putExtra(
1083                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1084                    ivs.getHostsString());
1085            verificationIntent.putExtra(
1086                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1087                    ivs.getPackageName());
1088            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1089            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1090
1091            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1092            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1093                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1094                    UserHandle.USER_SYSTEM, true, "intent filter verifier");
1095
1096            mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM);
1097            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1098                    "Sending IntentFilter verification broadcast");
1099        }
1100
1101        public void receiveVerificationResponse(int verificationId) {
1102            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1103
1104            final boolean verified = ivs.isVerified();
1105
1106            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1107            final int count = filters.size();
1108            if (DEBUG_DOMAIN_VERIFICATION) {
1109                Slog.i(TAG, "Received verification response " + verificationId
1110                        + " for " + count + " filters, verified=" + verified);
1111            }
1112            for (int n=0; n<count; n++) {
1113                PackageParser.ActivityIntentInfo filter = filters.get(n);
1114                filter.setVerified(verified);
1115
1116                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1117                        + " verified with result:" + verified + " and hosts:"
1118                        + ivs.getHostsString());
1119            }
1120
1121            mIntentFilterVerificationStates.remove(verificationId);
1122
1123            final String packageName = ivs.getPackageName();
1124            IntentFilterVerificationInfo ivi = null;
1125
1126            synchronized (mPackages) {
1127                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1128            }
1129            if (ivi == null) {
1130                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1131                        + verificationId + " packageName:" + packageName);
1132                return;
1133            }
1134            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1135                    "Updating IntentFilterVerificationInfo for package " + packageName
1136                            +" verificationId:" + verificationId);
1137
1138            synchronized (mPackages) {
1139                if (verified) {
1140                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1141                } else {
1142                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1143                }
1144                scheduleWriteSettingsLocked();
1145
1146                final int userId = ivs.getUserId();
1147                if (userId != UserHandle.USER_ALL) {
1148                    final int userStatus =
1149                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1150
1151                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1152                    boolean needUpdate = false;
1153
1154                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1155                    // already been set by the User thru the Disambiguation dialog
1156                    switch (userStatus) {
1157                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1158                            if (verified) {
1159                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1160                            } else {
1161                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1162                            }
1163                            needUpdate = true;
1164                            break;
1165
1166                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1167                            if (verified) {
1168                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1169                                needUpdate = true;
1170                            }
1171                            break;
1172
1173                        default:
1174                            // Nothing to do
1175                    }
1176
1177                    if (needUpdate) {
1178                        mSettings.updateIntentFilterVerificationStatusLPw(
1179                                packageName, updatedStatus, userId);
1180                        scheduleWritePackageRestrictionsLocked(userId);
1181                    }
1182                }
1183            }
1184        }
1185
1186        @Override
1187        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1188                    ActivityIntentInfo filter, String packageName) {
1189            if (!hasValidDomains(filter)) {
1190                return false;
1191            }
1192            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1193            if (ivs == null) {
1194                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1195                        packageName);
1196            }
1197            if (DEBUG_DOMAIN_VERIFICATION) {
1198                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1199            }
1200            ivs.addFilter(filter);
1201            return true;
1202        }
1203
1204        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1205                int userId, int verificationId, String packageName) {
1206            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1207                    verifierUid, userId, packageName);
1208            ivs.setPendingState();
1209            synchronized (mPackages) {
1210                mIntentFilterVerificationStates.append(verificationId, ivs);
1211                mCurrentIntentFilterVerifications.add(verificationId);
1212            }
1213            return ivs;
1214        }
1215    }
1216
1217    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1218        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1219                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1220                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1221    }
1222
1223    // Set of pending broadcasts for aggregating enable/disable of components.
1224    static class PendingPackageBroadcasts {
1225        // for each user id, a map of <package name -> components within that package>
1226        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1227
1228        public PendingPackageBroadcasts() {
1229            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1230        }
1231
1232        public ArrayList<String> get(int userId, String packageName) {
1233            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1234            return packages.get(packageName);
1235        }
1236
1237        public void put(int userId, String packageName, ArrayList<String> components) {
1238            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1239            packages.put(packageName, components);
1240        }
1241
1242        public void remove(int userId, String packageName) {
1243            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1244            if (packages != null) {
1245                packages.remove(packageName);
1246            }
1247        }
1248
1249        public void remove(int userId) {
1250            mUidMap.remove(userId);
1251        }
1252
1253        public int userIdCount() {
1254            return mUidMap.size();
1255        }
1256
1257        public int userIdAt(int n) {
1258            return mUidMap.keyAt(n);
1259        }
1260
1261        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1262            return mUidMap.get(userId);
1263        }
1264
1265        public int size() {
1266            // total number of pending broadcast entries across all userIds
1267            int num = 0;
1268            for (int i = 0; i< mUidMap.size(); i++) {
1269                num += mUidMap.valueAt(i).size();
1270            }
1271            return num;
1272        }
1273
1274        public void clear() {
1275            mUidMap.clear();
1276        }
1277
1278        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1279            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1280            if (map == null) {
1281                map = new ArrayMap<String, ArrayList<String>>();
1282                mUidMap.put(userId, map);
1283            }
1284            return map;
1285        }
1286    }
1287    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1288
1289    // Service Connection to remote media container service to copy
1290    // package uri's from external media onto secure containers
1291    // or internal storage.
1292    private IMediaContainerService mContainerService = null;
1293
1294    static final int SEND_PENDING_BROADCAST = 1;
1295    static final int MCS_BOUND = 3;
1296    static final int END_COPY = 4;
1297    static final int INIT_COPY = 5;
1298    static final int MCS_UNBIND = 6;
1299    static final int START_CLEANING_PACKAGE = 7;
1300    static final int FIND_INSTALL_LOC = 8;
1301    static final int POST_INSTALL = 9;
1302    static final int MCS_RECONNECT = 10;
1303    static final int MCS_GIVE_UP = 11;
1304    static final int UPDATED_MEDIA_STATUS = 12;
1305    static final int WRITE_SETTINGS = 13;
1306    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1307    static final int PACKAGE_VERIFIED = 15;
1308    static final int CHECK_PENDING_VERIFICATION = 16;
1309    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1310    static final int INTENT_FILTER_VERIFIED = 18;
1311    static final int WRITE_PACKAGE_LIST = 19;
1312    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1313
1314    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1315
1316    // Delay time in millisecs
1317    static final int BROADCAST_DELAY = 10 * 1000;
1318
1319    private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1320            2 * 60 * 60 * 1000L; /* two hours */
1321
1322    static UserManagerService sUserManager;
1323
1324    // Stores a list of users whose package restrictions file needs to be updated
1325    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1326
1327    final private DefaultContainerConnection mDefContainerConn =
1328            new DefaultContainerConnection();
1329    class DefaultContainerConnection implements ServiceConnection {
1330        public void onServiceConnected(ComponentName name, IBinder service) {
1331            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1332            final IMediaContainerService imcs = IMediaContainerService.Stub
1333                    .asInterface(Binder.allowBlocking(service));
1334            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1335        }
1336
1337        public void onServiceDisconnected(ComponentName name) {
1338            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1339        }
1340    }
1341
1342    // Recordkeeping of restore-after-install operations that are currently in flight
1343    // between the Package Manager and the Backup Manager
1344    static class PostInstallData {
1345        public InstallArgs args;
1346        public PackageInstalledInfo res;
1347
1348        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1349            args = _a;
1350            res = _r;
1351        }
1352    }
1353
1354    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1355    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1356
1357    // XML tags for backup/restore of various bits of state
1358    private static final String TAG_PREFERRED_BACKUP = "pa";
1359    private static final String TAG_DEFAULT_APPS = "da";
1360    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1361
1362    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1363    private static final String TAG_ALL_GRANTS = "rt-grants";
1364    private static final String TAG_GRANT = "grant";
1365    private static final String ATTR_PACKAGE_NAME = "pkg";
1366
1367    private static final String TAG_PERMISSION = "perm";
1368    private static final String ATTR_PERMISSION_NAME = "name";
1369    private static final String ATTR_IS_GRANTED = "g";
1370    private static final String ATTR_USER_SET = "set";
1371    private static final String ATTR_USER_FIXED = "fixed";
1372    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1373
1374    // System/policy permission grants are not backed up
1375    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1376            FLAG_PERMISSION_POLICY_FIXED
1377            | FLAG_PERMISSION_SYSTEM_FIXED
1378            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1379
1380    // And we back up these user-adjusted states
1381    private static final int USER_RUNTIME_GRANT_MASK =
1382            FLAG_PERMISSION_USER_SET
1383            | FLAG_PERMISSION_USER_FIXED
1384            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1385
1386    final @Nullable String mRequiredVerifierPackage;
1387    final @NonNull String mRequiredInstallerPackage;
1388    final @NonNull String mRequiredUninstallerPackage;
1389    final @Nullable String mSetupWizardPackage;
1390    final @Nullable String mStorageManagerPackage;
1391    final @NonNull String mServicesSystemSharedLibraryPackageName;
1392    final @NonNull String mSharedSystemSharedLibraryPackageName;
1393
1394    final boolean mPermissionReviewRequired;
1395
1396    private final PackageUsage mPackageUsage = new PackageUsage();
1397    private final CompilerStats mCompilerStats = new CompilerStats();
1398
1399    class PackageHandler extends Handler {
1400        private boolean mBound = false;
1401        final ArrayList<HandlerParams> mPendingInstalls =
1402            new ArrayList<HandlerParams>();
1403
1404        private boolean connectToService() {
1405            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1406                    " DefaultContainerService");
1407            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1408            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1409            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1410                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1411                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1412                mBound = true;
1413                return true;
1414            }
1415            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1416            return false;
1417        }
1418
1419        private void disconnectService() {
1420            mContainerService = null;
1421            mBound = false;
1422            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1423            mContext.unbindService(mDefContainerConn);
1424            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1425        }
1426
1427        PackageHandler(Looper looper) {
1428            super(looper);
1429        }
1430
1431        public void handleMessage(Message msg) {
1432            try {
1433                doHandleMessage(msg);
1434            } finally {
1435                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1436            }
1437        }
1438
1439        void doHandleMessage(Message msg) {
1440            switch (msg.what) {
1441                case INIT_COPY: {
1442                    HandlerParams params = (HandlerParams) msg.obj;
1443                    int idx = mPendingInstalls.size();
1444                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1445                    // If a bind was already initiated we dont really
1446                    // need to do anything. The pending install
1447                    // will be processed later on.
1448                    if (!mBound) {
1449                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1450                                System.identityHashCode(mHandler));
1451                        // If this is the only one pending we might
1452                        // have to bind to the service again.
1453                        if (!connectToService()) {
1454                            Slog.e(TAG, "Failed to bind to media container service");
1455                            params.serviceError();
1456                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1457                                    System.identityHashCode(mHandler));
1458                            if (params.traceMethod != null) {
1459                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1460                                        params.traceCookie);
1461                            }
1462                            return;
1463                        } else {
1464                            // Once we bind to the service, the first
1465                            // pending request will be processed.
1466                            mPendingInstalls.add(idx, params);
1467                        }
1468                    } else {
1469                        mPendingInstalls.add(idx, params);
1470                        // Already bound to the service. Just make
1471                        // sure we trigger off processing the first request.
1472                        if (idx == 0) {
1473                            mHandler.sendEmptyMessage(MCS_BOUND);
1474                        }
1475                    }
1476                    break;
1477                }
1478                case MCS_BOUND: {
1479                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1480                    if (msg.obj != null) {
1481                        mContainerService = (IMediaContainerService) msg.obj;
1482                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1483                                System.identityHashCode(mHandler));
1484                    }
1485                    if (mContainerService == null) {
1486                        if (!mBound) {
1487                            // Something seriously wrong since we are not bound and we are not
1488                            // waiting for connection. Bail out.
1489                            Slog.e(TAG, "Cannot bind to media container service");
1490                            for (HandlerParams params : mPendingInstalls) {
1491                                // Indicate service bind error
1492                                params.serviceError();
1493                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1494                                        System.identityHashCode(params));
1495                                if (params.traceMethod != null) {
1496                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1497                                            params.traceMethod, params.traceCookie);
1498                                }
1499                                return;
1500                            }
1501                            mPendingInstalls.clear();
1502                        } else {
1503                            Slog.w(TAG, "Waiting to connect to media container service");
1504                        }
1505                    } else if (mPendingInstalls.size() > 0) {
1506                        HandlerParams params = mPendingInstalls.get(0);
1507                        if (params != null) {
1508                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1509                                    System.identityHashCode(params));
1510                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1511                            if (params.startCopy()) {
1512                                // We are done...  look for more work or to
1513                                // go idle.
1514                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1515                                        "Checking for more work or unbind...");
1516                                // Delete pending install
1517                                if (mPendingInstalls.size() > 0) {
1518                                    mPendingInstalls.remove(0);
1519                                }
1520                                if (mPendingInstalls.size() == 0) {
1521                                    if (mBound) {
1522                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1523                                                "Posting delayed MCS_UNBIND");
1524                                        removeMessages(MCS_UNBIND);
1525                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1526                                        // Unbind after a little delay, to avoid
1527                                        // continual thrashing.
1528                                        sendMessageDelayed(ubmsg, 10000);
1529                                    }
1530                                } else {
1531                                    // There are more pending requests in queue.
1532                                    // Just post MCS_BOUND message to trigger processing
1533                                    // of next pending install.
1534                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1535                                            "Posting MCS_BOUND for next work");
1536                                    mHandler.sendEmptyMessage(MCS_BOUND);
1537                                }
1538                            }
1539                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1540                        }
1541                    } else {
1542                        // Should never happen ideally.
1543                        Slog.w(TAG, "Empty queue");
1544                    }
1545                    break;
1546                }
1547                case MCS_RECONNECT: {
1548                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1549                    if (mPendingInstalls.size() > 0) {
1550                        if (mBound) {
1551                            disconnectService();
1552                        }
1553                        if (!connectToService()) {
1554                            Slog.e(TAG, "Failed to bind to media container service");
1555                            for (HandlerParams params : mPendingInstalls) {
1556                                // Indicate service bind error
1557                                params.serviceError();
1558                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1559                                        System.identityHashCode(params));
1560                            }
1561                            mPendingInstalls.clear();
1562                        }
1563                    }
1564                    break;
1565                }
1566                case MCS_UNBIND: {
1567                    // If there is no actual work left, then time to unbind.
1568                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1569
1570                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1571                        if (mBound) {
1572                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1573
1574                            disconnectService();
1575                        }
1576                    } else if (mPendingInstalls.size() > 0) {
1577                        // There are more pending requests in queue.
1578                        // Just post MCS_BOUND message to trigger processing
1579                        // of next pending install.
1580                        mHandler.sendEmptyMessage(MCS_BOUND);
1581                    }
1582
1583                    break;
1584                }
1585                case MCS_GIVE_UP: {
1586                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1587                    HandlerParams params = mPendingInstalls.remove(0);
1588                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1589                            System.identityHashCode(params));
1590                    break;
1591                }
1592                case SEND_PENDING_BROADCAST: {
1593                    String packages[];
1594                    ArrayList<String> components[];
1595                    int size = 0;
1596                    int uids[];
1597                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1598                    synchronized (mPackages) {
1599                        if (mPendingBroadcasts == null) {
1600                            return;
1601                        }
1602                        size = mPendingBroadcasts.size();
1603                        if (size <= 0) {
1604                            // Nothing to be done. Just return
1605                            return;
1606                        }
1607                        packages = new String[size];
1608                        components = new ArrayList[size];
1609                        uids = new int[size];
1610                        int i = 0;  // filling out the above arrays
1611
1612                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1613                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1614                            Iterator<Map.Entry<String, ArrayList<String>>> it
1615                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1616                                            .entrySet().iterator();
1617                            while (it.hasNext() && i < size) {
1618                                Map.Entry<String, ArrayList<String>> ent = it.next();
1619                                packages[i] = ent.getKey();
1620                                components[i] = ent.getValue();
1621                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1622                                uids[i] = (ps != null)
1623                                        ? UserHandle.getUid(packageUserId, ps.appId)
1624                                        : -1;
1625                                i++;
1626                            }
1627                        }
1628                        size = i;
1629                        mPendingBroadcasts.clear();
1630                    }
1631                    // Send broadcasts
1632                    for (int i = 0; i < size; i++) {
1633                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1634                    }
1635                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1636                    break;
1637                }
1638                case START_CLEANING_PACKAGE: {
1639                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1640                    final String packageName = (String)msg.obj;
1641                    final int userId = msg.arg1;
1642                    final boolean andCode = msg.arg2 != 0;
1643                    synchronized (mPackages) {
1644                        if (userId == UserHandle.USER_ALL) {
1645                            int[] users = sUserManager.getUserIds();
1646                            for (int user : users) {
1647                                mSettings.addPackageToCleanLPw(
1648                                        new PackageCleanItem(user, packageName, andCode));
1649                            }
1650                        } else {
1651                            mSettings.addPackageToCleanLPw(
1652                                    new PackageCleanItem(userId, packageName, andCode));
1653                        }
1654                    }
1655                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1656                    startCleaningPackages();
1657                } break;
1658                case POST_INSTALL: {
1659                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1660
1661                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1662                    final boolean didRestore = (msg.arg2 != 0);
1663                    mRunningInstalls.delete(msg.arg1);
1664
1665                    if (data != null) {
1666                        InstallArgs args = data.args;
1667                        PackageInstalledInfo parentRes = data.res;
1668
1669                        final boolean grantPermissions = (args.installFlags
1670                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1671                        final boolean killApp = (args.installFlags
1672                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1673                        final String[] grantedPermissions = args.installGrantPermissions;
1674
1675                        // Handle the parent package
1676                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1677                                grantedPermissions, didRestore, args.installerPackageName,
1678                                args.observer);
1679
1680                        // Handle the child packages
1681                        final int childCount = (parentRes.addedChildPackages != null)
1682                                ? parentRes.addedChildPackages.size() : 0;
1683                        for (int i = 0; i < childCount; i++) {
1684                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1685                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1686                                    grantedPermissions, false, args.installerPackageName,
1687                                    args.observer);
1688                        }
1689
1690                        // Log tracing if needed
1691                        if (args.traceMethod != null) {
1692                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1693                                    args.traceCookie);
1694                        }
1695                    } else {
1696                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1697                    }
1698
1699                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1700                } break;
1701                case UPDATED_MEDIA_STATUS: {
1702                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1703                    boolean reportStatus = msg.arg1 == 1;
1704                    boolean doGc = msg.arg2 == 1;
1705                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1706                    if (doGc) {
1707                        // Force a gc to clear up stale containers.
1708                        Runtime.getRuntime().gc();
1709                    }
1710                    if (msg.obj != null) {
1711                        @SuppressWarnings("unchecked")
1712                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1713                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1714                        // Unload containers
1715                        unloadAllContainers(args);
1716                    }
1717                    if (reportStatus) {
1718                        try {
1719                            if (DEBUG_SD_INSTALL) Log.i(TAG,
1720                                    "Invoking StorageManagerService call back");
1721                            PackageHelper.getStorageManager().finishMediaUpdate();
1722                        } catch (RemoteException e) {
1723                            Log.e(TAG, "StorageManagerService not running?");
1724                        }
1725                    }
1726                } break;
1727                case WRITE_SETTINGS: {
1728                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1729                    synchronized (mPackages) {
1730                        removeMessages(WRITE_SETTINGS);
1731                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1732                        mSettings.writeLPr();
1733                        mDirtyUsers.clear();
1734                    }
1735                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1736                } break;
1737                case WRITE_PACKAGE_RESTRICTIONS: {
1738                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1739                    synchronized (mPackages) {
1740                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1741                        for (int userId : mDirtyUsers) {
1742                            mSettings.writePackageRestrictionsLPr(userId);
1743                        }
1744                        mDirtyUsers.clear();
1745                    }
1746                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1747                } break;
1748                case WRITE_PACKAGE_LIST: {
1749                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1750                    synchronized (mPackages) {
1751                        removeMessages(WRITE_PACKAGE_LIST);
1752                        mSettings.writePackageListLPr(msg.arg1);
1753                    }
1754                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1755                } break;
1756                case CHECK_PENDING_VERIFICATION: {
1757                    final int verificationId = msg.arg1;
1758                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1759
1760                    if ((state != null) && !state.timeoutExtended()) {
1761                        final InstallArgs args = state.getInstallArgs();
1762                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1763
1764                        Slog.i(TAG, "Verification timed out for " + originUri);
1765                        mPendingVerification.remove(verificationId);
1766
1767                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1768
1769                        final UserHandle user = args.getUser();
1770                        if (getDefaultVerificationResponse(user)
1771                                == PackageManager.VERIFICATION_ALLOW) {
1772                            Slog.i(TAG, "Continuing with installation of " + originUri);
1773                            state.setVerifierResponse(Binder.getCallingUid(),
1774                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1775                            broadcastPackageVerified(verificationId, originUri,
1776                                    PackageManager.VERIFICATION_ALLOW, user);
1777                            try {
1778                                ret = args.copyApk(mContainerService, true);
1779                            } catch (RemoteException e) {
1780                                Slog.e(TAG, "Could not contact the ContainerService");
1781                            }
1782                        } else {
1783                            broadcastPackageVerified(verificationId, originUri,
1784                                    PackageManager.VERIFICATION_REJECT, user);
1785                        }
1786
1787                        Trace.asyncTraceEnd(
1788                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1789
1790                        processPendingInstall(args, ret);
1791                        mHandler.sendEmptyMessage(MCS_UNBIND);
1792                    }
1793                    break;
1794                }
1795                case PACKAGE_VERIFIED: {
1796                    final int verificationId = msg.arg1;
1797
1798                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1799                    if (state == null) {
1800                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1801                        break;
1802                    }
1803
1804                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1805
1806                    state.setVerifierResponse(response.callerUid, response.code);
1807
1808                    if (state.isVerificationComplete()) {
1809                        mPendingVerification.remove(verificationId);
1810
1811                        final InstallArgs args = state.getInstallArgs();
1812                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1813
1814                        int ret;
1815                        if (state.isInstallAllowed()) {
1816                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1817                            broadcastPackageVerified(verificationId, originUri,
1818                                    response.code, state.getInstallArgs().getUser());
1819                            try {
1820                                ret = args.copyApk(mContainerService, true);
1821                            } catch (RemoteException e) {
1822                                Slog.e(TAG, "Could not contact the ContainerService");
1823                            }
1824                        } else {
1825                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1826                        }
1827
1828                        Trace.asyncTraceEnd(
1829                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1830
1831                        processPendingInstall(args, ret);
1832                        mHandler.sendEmptyMessage(MCS_UNBIND);
1833                    }
1834
1835                    break;
1836                }
1837                case START_INTENT_FILTER_VERIFICATIONS: {
1838                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1839                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1840                            params.replacing, params.pkg);
1841                    break;
1842                }
1843                case INTENT_FILTER_VERIFIED: {
1844                    final int verificationId = msg.arg1;
1845
1846                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1847                            verificationId);
1848                    if (state == null) {
1849                        Slog.w(TAG, "Invalid IntentFilter verification token "
1850                                + verificationId + " received");
1851                        break;
1852                    }
1853
1854                    final int userId = state.getUserId();
1855
1856                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1857                            "Processing IntentFilter verification with token:"
1858                            + verificationId + " and userId:" + userId);
1859
1860                    final IntentFilterVerificationResponse response =
1861                            (IntentFilterVerificationResponse) msg.obj;
1862
1863                    state.setVerifierResponse(response.callerUid, response.code);
1864
1865                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1866                            "IntentFilter verification with token:" + verificationId
1867                            + " and userId:" + userId
1868                            + " is settings verifier response with response code:"
1869                            + response.code);
1870
1871                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1872                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1873                                + response.getFailedDomainsString());
1874                    }
1875
1876                    if (state.isVerificationComplete()) {
1877                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1878                    } else {
1879                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1880                                "IntentFilter verification with token:" + verificationId
1881                                + " was not said to be complete");
1882                    }
1883
1884                    break;
1885                }
1886                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1887                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1888                            mInstantAppResolverConnection,
1889                            (InstantAppRequest) msg.obj,
1890                            mInstantAppInstallerActivity,
1891                            mHandler);
1892                }
1893            }
1894        }
1895    }
1896
1897    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1898            boolean killApp, String[] grantedPermissions,
1899            boolean launchedForRestore, String installerPackage,
1900            IPackageInstallObserver2 installObserver) {
1901        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1902            // Send the removed broadcasts
1903            if (res.removedInfo != null) {
1904                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1905            }
1906
1907            // Now that we successfully installed the package, grant runtime
1908            // permissions if requested before broadcasting the install. Also
1909            // for legacy apps in permission review mode we clear the permission
1910            // review flag which is used to emulate runtime permissions for
1911            // legacy apps.
1912            if (grantPermissions) {
1913                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1914            }
1915
1916            final boolean update = res.removedInfo != null
1917                    && res.removedInfo.removedPackage != null;
1918            final String origInstallerPackageName = res.removedInfo != null
1919                    ? res.removedInfo.installerPackageName : null;
1920
1921            // If this is the first time we have child packages for a disabled privileged
1922            // app that had no children, we grant requested runtime permissions to the new
1923            // children if the parent on the system image had them already granted.
1924            if (res.pkg.parentPackage != null) {
1925                synchronized (mPackages) {
1926                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1927                }
1928            }
1929
1930            synchronized (mPackages) {
1931                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1932            }
1933
1934            final String packageName = res.pkg.applicationInfo.packageName;
1935
1936            // Determine the set of users who are adding this package for
1937            // the first time vs. those who are seeing an update.
1938            int[] firstUsers = EMPTY_INT_ARRAY;
1939            int[] updateUsers = EMPTY_INT_ARRAY;
1940            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1941            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1942            for (int newUser : res.newUsers) {
1943                if (ps.getInstantApp(newUser)) {
1944                    continue;
1945                }
1946                if (allNewUsers) {
1947                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1948                    continue;
1949                }
1950                boolean isNew = true;
1951                for (int origUser : res.origUsers) {
1952                    if (origUser == newUser) {
1953                        isNew = false;
1954                        break;
1955                    }
1956                }
1957                if (isNew) {
1958                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1959                } else {
1960                    updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1961                }
1962            }
1963
1964            // Send installed broadcasts if the package is not a static shared lib.
1965            if (res.pkg.staticSharedLibName == null) {
1966                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1967
1968                // Send added for users that see the package for the first time
1969                // sendPackageAddedForNewUsers also deals with system apps
1970                int appId = UserHandle.getAppId(res.uid);
1971                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1972                sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers);
1973
1974                // Send added for users that don't see the package for the first time
1975                Bundle extras = new Bundle(1);
1976                extras.putInt(Intent.EXTRA_UID, res.uid);
1977                if (update) {
1978                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1979                }
1980                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1981                        extras, 0 /*flags*/,
1982                        null /*targetPackage*/, null /*finishedReceiver*/, updateUsers);
1983                if (origInstallerPackageName != null) {
1984                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1985                            extras, 0 /*flags*/,
1986                            origInstallerPackageName, null /*finishedReceiver*/, updateUsers);
1987                }
1988
1989                // Send replaced for users that don't see the package for the first time
1990                if (update) {
1991                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1992                            packageName, extras, 0 /*flags*/,
1993                            null /*targetPackage*/, null /*finishedReceiver*/,
1994                            updateUsers);
1995                    if (origInstallerPackageName != null) {
1996                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
1997                                extras, 0 /*flags*/,
1998                                origInstallerPackageName, null /*finishedReceiver*/, updateUsers);
1999                    }
2000                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
2001                            null /*package*/, null /*extras*/, 0 /*flags*/,
2002                            packageName /*targetPackage*/,
2003                            null /*finishedReceiver*/, updateUsers);
2004                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
2005                    // First-install and we did a restore, so we're responsible for the
2006                    // first-launch broadcast.
2007                    if (DEBUG_BACKUP) {
2008                        Slog.i(TAG, "Post-restore of " + packageName
2009                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
2010                    }
2011                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
2012                }
2013
2014                // Send broadcast package appeared if forward locked/external for all users
2015                // treat asec-hosted packages like removable media on upgrade
2016                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2017                    if (DEBUG_INSTALL) {
2018                        Slog.i(TAG, "upgrading pkg " + res.pkg
2019                                + " is ASEC-hosted -> AVAILABLE");
2020                    }
2021                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2022                    ArrayList<String> pkgList = new ArrayList<>(1);
2023                    pkgList.add(packageName);
2024                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2025                }
2026            }
2027
2028            // Work that needs to happen on first install within each user
2029            if (firstUsers != null && firstUsers.length > 0) {
2030                synchronized (mPackages) {
2031                    for (int userId : firstUsers) {
2032                        // If this app is a browser and it's newly-installed for some
2033                        // users, clear any default-browser state in those users. The
2034                        // app's nature doesn't depend on the user, so we can just check
2035                        // its browser nature in any user and generalize.
2036                        if (packageIsBrowser(packageName, userId)) {
2037                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2038                        }
2039
2040                        // We may also need to apply pending (restored) runtime
2041                        // permission grants within these users.
2042                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2043                    }
2044                }
2045            }
2046
2047            // Log current value of "unknown sources" setting
2048            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2049                    getUnknownSourcesSettings());
2050
2051            // Remove the replaced package's older resources safely now
2052            // We delete after a gc for applications  on sdcard.
2053            if (res.removedInfo != null && res.removedInfo.args != null) {
2054                Runtime.getRuntime().gc();
2055                synchronized (mInstallLock) {
2056                    res.removedInfo.args.doPostDeleteLI(true);
2057                }
2058            } else {
2059                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2060                // and not block here.
2061                VMRuntime.getRuntime().requestConcurrentGC();
2062            }
2063
2064            // Notify DexManager that the package was installed for new users.
2065            // The updated users should already be indexed and the package code paths
2066            // should not change.
2067            // Don't notify the manager for ephemeral apps as they are not expected to
2068            // survive long enough to benefit of background optimizations.
2069            for (int userId : firstUsers) {
2070                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2071                // There's a race currently where some install events may interleave with an uninstall.
2072                // This can lead to package info being null (b/36642664).
2073                if (info != null) {
2074                    mDexManager.notifyPackageInstalled(info, userId);
2075                }
2076            }
2077        }
2078
2079        // If someone is watching installs - notify them
2080        if (installObserver != null) {
2081            try {
2082                Bundle extras = extrasForInstallResult(res);
2083                installObserver.onPackageInstalled(res.name, res.returnCode,
2084                        res.returnMsg, extras);
2085            } catch (RemoteException e) {
2086                Slog.i(TAG, "Observer no longer exists.");
2087            }
2088        }
2089    }
2090
2091    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
2092            PackageParser.Package pkg) {
2093        if (pkg.parentPackage == null) {
2094            return;
2095        }
2096        if (pkg.requestedPermissions == null) {
2097            return;
2098        }
2099        final PackageSetting disabledSysParentPs = mSettings
2100                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
2101        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
2102                || !disabledSysParentPs.isPrivileged()
2103                || (disabledSysParentPs.childPackageNames != null
2104                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
2105            return;
2106        }
2107        final int[] allUserIds = sUserManager.getUserIds();
2108        final int permCount = pkg.requestedPermissions.size();
2109        for (int i = 0; i < permCount; i++) {
2110            String permission = pkg.requestedPermissions.get(i);
2111            BasePermission bp = mSettings.mPermissions.get(permission);
2112            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
2113                continue;
2114            }
2115            for (int userId : allUserIds) {
2116                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
2117                        permission, userId)) {
2118                    grantRuntimePermission(pkg.packageName, permission, userId);
2119                }
2120            }
2121        }
2122    }
2123
2124    private StorageEventListener mStorageListener = new StorageEventListener() {
2125        @Override
2126        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2127            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2128                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2129                    final String volumeUuid = vol.getFsUuid();
2130
2131                    // Clean up any users or apps that were removed or recreated
2132                    // while this volume was missing
2133                    sUserManager.reconcileUsers(volumeUuid);
2134                    reconcileApps(volumeUuid);
2135
2136                    // Clean up any install sessions that expired or were
2137                    // cancelled while this volume was missing
2138                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2139
2140                    loadPrivatePackages(vol);
2141
2142                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2143                    unloadPrivatePackages(vol);
2144                }
2145            }
2146
2147            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
2148                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2149                    updateExternalMediaStatus(true, false);
2150                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2151                    updateExternalMediaStatus(false, false);
2152                }
2153            }
2154        }
2155
2156        @Override
2157        public void onVolumeForgotten(String fsUuid) {
2158            if (TextUtils.isEmpty(fsUuid)) {
2159                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2160                return;
2161            }
2162
2163            // Remove any apps installed on the forgotten volume
2164            synchronized (mPackages) {
2165                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2166                for (PackageSetting ps : packages) {
2167                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2168                    deletePackageVersioned(new VersionedPackage(ps.name,
2169                            PackageManager.VERSION_CODE_HIGHEST),
2170                            new LegacyPackageDeleteObserver(null).getBinder(),
2171                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2172                    // Try very hard to release any references to this package
2173                    // so we don't risk the system server being killed due to
2174                    // open FDs
2175                    AttributeCache.instance().removePackage(ps.name);
2176                }
2177
2178                mSettings.onVolumeForgotten(fsUuid);
2179                mSettings.writeLPr();
2180            }
2181        }
2182    };
2183
2184    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2185            String[] grantedPermissions) {
2186        for (int userId : userIds) {
2187            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2188        }
2189    }
2190
2191    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2192            String[] grantedPermissions) {
2193        PackageSetting ps = (PackageSetting) pkg.mExtras;
2194        if (ps == null) {
2195            return;
2196        }
2197
2198        PermissionsState permissionsState = ps.getPermissionsState();
2199
2200        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2201                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2202
2203        final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
2204                >= Build.VERSION_CODES.M;
2205
2206        final boolean instantApp = isInstantApp(pkg.packageName, userId);
2207
2208        for (String permission : pkg.requestedPermissions) {
2209            final BasePermission bp;
2210            synchronized (mPackages) {
2211                bp = mSettings.mPermissions.get(permission);
2212            }
2213            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2214                    && (!instantApp || bp.isInstant())
2215                    && (supportsRuntimePermissions || !bp.isRuntimeOnly())
2216                    && (grantedPermissions == null
2217                           || ArrayUtils.contains(grantedPermissions, permission))) {
2218                final int flags = permissionsState.getPermissionFlags(permission, userId);
2219                if (supportsRuntimePermissions) {
2220                    // Installer cannot change immutable permissions.
2221                    if ((flags & immutableFlags) == 0) {
2222                        grantRuntimePermission(pkg.packageName, permission, userId);
2223                    }
2224                } else if (mPermissionReviewRequired) {
2225                    // In permission review mode we clear the review flag when we
2226                    // are asked to install the app with all permissions granted.
2227                    if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
2228                        updatePermissionFlags(permission, pkg.packageName,
2229                                PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId);
2230                    }
2231                }
2232            }
2233        }
2234    }
2235
2236    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2237        Bundle extras = null;
2238        switch (res.returnCode) {
2239            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2240                extras = new Bundle();
2241                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2242                        res.origPermission);
2243                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2244                        res.origPackage);
2245                break;
2246            }
2247            case PackageManager.INSTALL_SUCCEEDED: {
2248                extras = new Bundle();
2249                extras.putBoolean(Intent.EXTRA_REPLACING,
2250                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2251                break;
2252            }
2253        }
2254        return extras;
2255    }
2256
2257    void scheduleWriteSettingsLocked() {
2258        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2259            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2260        }
2261    }
2262
2263    void scheduleWritePackageListLocked(int userId) {
2264        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2265            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2266            msg.arg1 = userId;
2267            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2268        }
2269    }
2270
2271    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2272        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2273        scheduleWritePackageRestrictionsLocked(userId);
2274    }
2275
2276    void scheduleWritePackageRestrictionsLocked(int userId) {
2277        final int[] userIds = (userId == UserHandle.USER_ALL)
2278                ? sUserManager.getUserIds() : new int[]{userId};
2279        for (int nextUserId : userIds) {
2280            if (!sUserManager.exists(nextUserId)) return;
2281            mDirtyUsers.add(nextUserId);
2282            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2283                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2284            }
2285        }
2286    }
2287
2288    public static PackageManagerService main(Context context, Installer installer,
2289            boolean factoryTest, boolean onlyCore) {
2290        // Self-check for initial settings.
2291        PackageManagerServiceCompilerMapping.checkProperties();
2292
2293        PackageManagerService m = new PackageManagerService(context, installer,
2294                factoryTest, onlyCore);
2295        m.enableSystemUserPackages();
2296        ServiceManager.addService("package", m);
2297        return m;
2298    }
2299
2300    private void enableSystemUserPackages() {
2301        if (!UserManager.isSplitSystemUser()) {
2302            return;
2303        }
2304        // For system user, enable apps based on the following conditions:
2305        // - app is whitelisted or belong to one of these groups:
2306        //   -- system app which has no launcher icons
2307        //   -- system app which has INTERACT_ACROSS_USERS permission
2308        //   -- system IME app
2309        // - app is not in the blacklist
2310        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2311        Set<String> enableApps = new ArraySet<>();
2312        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2313                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2314                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2315        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2316        enableApps.addAll(wlApps);
2317        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2318                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2319        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2320        enableApps.removeAll(blApps);
2321        Log.i(TAG, "Applications installed for system user: " + enableApps);
2322        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2323                UserHandle.SYSTEM);
2324        final int allAppsSize = allAps.size();
2325        synchronized (mPackages) {
2326            for (int i = 0; i < allAppsSize; i++) {
2327                String pName = allAps.get(i);
2328                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2329                // Should not happen, but we shouldn't be failing if it does
2330                if (pkgSetting == null) {
2331                    continue;
2332                }
2333                boolean install = enableApps.contains(pName);
2334                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2335                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2336                            + " for system user");
2337                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2338                }
2339            }
2340            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2341        }
2342    }
2343
2344    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2345        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2346                Context.DISPLAY_SERVICE);
2347        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2348    }
2349
2350    /**
2351     * Requests that files preopted on a secondary system partition be copied to the data partition
2352     * if possible.  Note that the actual copying of the files is accomplished by init for security
2353     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2354     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2355     */
2356    private static void requestCopyPreoptedFiles() {
2357        final int WAIT_TIME_MS = 100;
2358        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2359        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2360            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2361            // We will wait for up to 100 seconds.
2362            final long timeStart = SystemClock.uptimeMillis();
2363            final long timeEnd = timeStart + 100 * 1000;
2364            long timeNow = timeStart;
2365            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2366                try {
2367                    Thread.sleep(WAIT_TIME_MS);
2368                } catch (InterruptedException e) {
2369                    // Do nothing
2370                }
2371                timeNow = SystemClock.uptimeMillis();
2372                if (timeNow > timeEnd) {
2373                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2374                    Slog.wtf(TAG, "cppreopt did not finish!");
2375                    break;
2376                }
2377            }
2378
2379            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2380        }
2381    }
2382
2383    public PackageManagerService(Context context, Installer installer,
2384            boolean factoryTest, boolean onlyCore) {
2385        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2386        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2387        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2388                SystemClock.uptimeMillis());
2389
2390        if (mSdkVersion <= 0) {
2391            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2392        }
2393
2394        mContext = context;
2395
2396        mPermissionReviewRequired = context.getResources().getBoolean(
2397                R.bool.config_permissionReviewRequired);
2398
2399        mFactoryTest = factoryTest;
2400        mOnlyCore = onlyCore;
2401        mMetrics = new DisplayMetrics();
2402        mSettings = new Settings(mPackages);
2403        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2404                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2405        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2406                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2407        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2408                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2409        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2410                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2411        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2412                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2413        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2414                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2415
2416        String separateProcesses = SystemProperties.get("debug.separate_processes");
2417        if (separateProcesses != null && separateProcesses.length() > 0) {
2418            if ("*".equals(separateProcesses)) {
2419                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2420                mSeparateProcesses = null;
2421                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2422            } else {
2423                mDefParseFlags = 0;
2424                mSeparateProcesses = separateProcesses.split(",");
2425                Slog.w(TAG, "Running with debug.separate_processes: "
2426                        + separateProcesses);
2427            }
2428        } else {
2429            mDefParseFlags = 0;
2430            mSeparateProcesses = null;
2431        }
2432
2433        mInstaller = installer;
2434        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2435                "*dexopt*");
2436        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
2437        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2438
2439        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2440                FgThread.get().getLooper());
2441
2442        getDefaultDisplayMetrics(context, mMetrics);
2443
2444        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2445        SystemConfig systemConfig = SystemConfig.getInstance();
2446        mGlobalGids = systemConfig.getGlobalGids();
2447        mSystemPermissions = systemConfig.getSystemPermissions();
2448        mAvailableFeatures = systemConfig.getAvailableFeatures();
2449        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2450
2451        mProtectedPackages = new ProtectedPackages(mContext);
2452
2453        synchronized (mInstallLock) {
2454        // writer
2455        synchronized (mPackages) {
2456            mHandlerThread = new ServiceThread(TAG,
2457                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2458            mHandlerThread.start();
2459            mHandler = new PackageHandler(mHandlerThread.getLooper());
2460            mProcessLoggingHandler = new ProcessLoggingHandler();
2461            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2462
2463            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2464            mInstantAppRegistry = new InstantAppRegistry(this);
2465
2466            File dataDir = Environment.getDataDirectory();
2467            mAppInstallDir = new File(dataDir, "app");
2468            mAppLib32InstallDir = new File(dataDir, "app-lib");
2469            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2470            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2471            sUserManager = new UserManagerService(context, this,
2472                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2473
2474            // Propagate permission configuration in to package manager.
2475            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2476                    = systemConfig.getPermissions();
2477            for (int i=0; i<permConfig.size(); i++) {
2478                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2479                BasePermission bp = mSettings.mPermissions.get(perm.name);
2480                if (bp == null) {
2481                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2482                    mSettings.mPermissions.put(perm.name, bp);
2483                }
2484                if (perm.gids != null) {
2485                    bp.setGids(perm.gids, perm.perUser);
2486                }
2487            }
2488
2489            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2490            final int builtInLibCount = libConfig.size();
2491            for (int i = 0; i < builtInLibCount; i++) {
2492                String name = libConfig.keyAt(i);
2493                String path = libConfig.valueAt(i);
2494                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2495                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2496            }
2497
2498            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2499
2500            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2501            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2502            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2503
2504            // Clean up orphaned packages for which the code path doesn't exist
2505            // and they are an update to a system app - caused by bug/32321269
2506            final int packageSettingCount = mSettings.mPackages.size();
2507            for (int i = packageSettingCount - 1; i >= 0; i--) {
2508                PackageSetting ps = mSettings.mPackages.valueAt(i);
2509                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2510                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2511                    mSettings.mPackages.removeAt(i);
2512                    mSettings.enableSystemPackageLPw(ps.name);
2513                }
2514            }
2515
2516            if (mFirstBoot) {
2517                requestCopyPreoptedFiles();
2518            }
2519
2520            String customResolverActivity = Resources.getSystem().getString(
2521                    R.string.config_customResolverActivity);
2522            if (TextUtils.isEmpty(customResolverActivity)) {
2523                customResolverActivity = null;
2524            } else {
2525                mCustomResolverComponentName = ComponentName.unflattenFromString(
2526                        customResolverActivity);
2527            }
2528
2529            long startTime = SystemClock.uptimeMillis();
2530
2531            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2532                    startTime);
2533
2534            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2535            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2536
2537            if (bootClassPath == null) {
2538                Slog.w(TAG, "No BOOTCLASSPATH found!");
2539            }
2540
2541            if (systemServerClassPath == null) {
2542                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2543            }
2544
2545            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2546
2547            final VersionInfo ver = mSettings.getInternalVersion();
2548            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2549            if (mIsUpgrade) {
2550                logCriticalInfo(Log.INFO,
2551                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2552            }
2553
2554            // when upgrading from pre-M, promote system app permissions from install to runtime
2555            mPromoteSystemApps =
2556                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2557
2558            // When upgrading from pre-N, we need to handle package extraction like first boot,
2559            // as there is no profiling data available.
2560            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2561
2562            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2563
2564            // save off the names of pre-existing system packages prior to scanning; we don't
2565            // want to automatically grant runtime permissions for new system apps
2566            if (mPromoteSystemApps) {
2567                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2568                while (pkgSettingIter.hasNext()) {
2569                    PackageSetting ps = pkgSettingIter.next();
2570                    if (isSystemApp(ps)) {
2571                        mExistingSystemPackages.add(ps.name);
2572                    }
2573                }
2574            }
2575
2576            mCacheDir = preparePackageParserCache(mIsUpgrade);
2577
2578            // Set flag to monitor and not change apk file paths when
2579            // scanning install directories.
2580            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2581
2582            if (mIsUpgrade || mFirstBoot) {
2583                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2584            }
2585
2586            // Collect vendor overlay packages. (Do this before scanning any apps.)
2587            // For security and version matching reason, only consider
2588            // overlay packages if they reside in the right directory.
2589            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2590                    | PackageParser.PARSE_IS_SYSTEM
2591                    | PackageParser.PARSE_IS_SYSTEM_DIR
2592                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2593
2594            mParallelPackageParserCallback.findStaticOverlayPackages();
2595
2596            // Find base frameworks (resource packages without code).
2597            scanDirTracedLI(frameworkDir, mDefParseFlags
2598                    | PackageParser.PARSE_IS_SYSTEM
2599                    | PackageParser.PARSE_IS_SYSTEM_DIR
2600                    | PackageParser.PARSE_IS_PRIVILEGED,
2601                    scanFlags | SCAN_NO_DEX, 0);
2602
2603            // Collected privileged system packages.
2604            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2605            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2606                    | PackageParser.PARSE_IS_SYSTEM
2607                    | PackageParser.PARSE_IS_SYSTEM_DIR
2608                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2609
2610            // Collect ordinary system packages.
2611            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2612            scanDirTracedLI(systemAppDir, mDefParseFlags
2613                    | PackageParser.PARSE_IS_SYSTEM
2614                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2615
2616            // Collect all vendor packages.
2617            File vendorAppDir = new File("/vendor/app");
2618            try {
2619                vendorAppDir = vendorAppDir.getCanonicalFile();
2620            } catch (IOException e) {
2621                // failed to look up canonical path, continue with original one
2622            }
2623            scanDirTracedLI(vendorAppDir, mDefParseFlags
2624                    | PackageParser.PARSE_IS_SYSTEM
2625                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2626
2627            // Collect all OEM packages.
2628            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2629            scanDirTracedLI(oemAppDir, mDefParseFlags
2630                    | PackageParser.PARSE_IS_SYSTEM
2631                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2632
2633            // Prune any system packages that no longer exist.
2634            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2635            if (!mOnlyCore) {
2636                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2637                while (psit.hasNext()) {
2638                    PackageSetting ps = psit.next();
2639
2640                    /*
2641                     * If this is not a system app, it can't be a
2642                     * disable system app.
2643                     */
2644                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2645                        continue;
2646                    }
2647
2648                    /*
2649                     * If the package is scanned, it's not erased.
2650                     */
2651                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2652                    if (scannedPkg != null) {
2653                        /*
2654                         * If the system app is both scanned and in the
2655                         * disabled packages list, then it must have been
2656                         * added via OTA. Remove it from the currently
2657                         * scanned package so the previously user-installed
2658                         * application can be scanned.
2659                         */
2660                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2661                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2662                                    + ps.name + "; removing system app.  Last known codePath="
2663                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2664                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2665                                    + scannedPkg.mVersionCode);
2666                            removePackageLI(scannedPkg, true);
2667                            mExpectingBetter.put(ps.name, ps.codePath);
2668                        }
2669
2670                        continue;
2671                    }
2672
2673                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2674                        psit.remove();
2675                        logCriticalInfo(Log.WARN, "System package " + ps.name
2676                                + " no longer exists; it's data will be wiped");
2677                        // Actual deletion of code and data will be handled by later
2678                        // reconciliation step
2679                    } else {
2680                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2681                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2682                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2683                        }
2684                    }
2685                }
2686            }
2687
2688            //look for any incomplete package installations
2689            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2690            for (int i = 0; i < deletePkgsList.size(); i++) {
2691                // Actual deletion of code and data will be handled by later
2692                // reconciliation step
2693                final String packageName = deletePkgsList.get(i).name;
2694                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2695                synchronized (mPackages) {
2696                    mSettings.removePackageLPw(packageName);
2697                }
2698            }
2699
2700            //delete tmp files
2701            deleteTempPackageFiles();
2702
2703            // Remove any shared userIDs that have no associated packages
2704            mSettings.pruneSharedUsersLPw();
2705            final long systemScanTime = SystemClock.uptimeMillis() - startTime;
2706            final int systemPackagesCount = mPackages.size();
2707            Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime
2708                    + " ms, packageCount: " + systemPackagesCount
2709                    + " ms, timePerPackage: "
2710                    + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount));
2711            if (mIsUpgrade && systemPackagesCount > 0) {
2712                MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time",
2713                        ((int) systemScanTime) / systemPackagesCount);
2714            }
2715            if (!mOnlyCore) {
2716                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2717                        SystemClock.uptimeMillis());
2718                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2719
2720                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2721                        | PackageParser.PARSE_FORWARD_LOCK,
2722                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2723
2724                /**
2725                 * Remove disable package settings for any updated system
2726                 * apps that were removed via an OTA. If they're not a
2727                 * previously-updated app, remove them completely.
2728                 * Otherwise, just revoke their system-level permissions.
2729                 */
2730                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2731                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2732                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2733
2734                    String msg;
2735                    if (deletedPkg == null) {
2736                        msg = "Updated system package " + deletedAppName
2737                                + " no longer exists; it's data will be wiped";
2738                        // Actual deletion of code and data will be handled by later
2739                        // reconciliation step
2740                    } else {
2741                        msg = "Updated system app + " + deletedAppName
2742                                + " no longer present; removing system privileges for "
2743                                + deletedAppName;
2744
2745                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2746
2747                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2748                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2749                    }
2750                    logCriticalInfo(Log.WARN, msg);
2751                }
2752
2753                /**
2754                 * Make sure all system apps that we expected to appear on
2755                 * the userdata partition actually showed up. If they never
2756                 * appeared, crawl back and revive the system version.
2757                 */
2758                for (int i = 0; i < mExpectingBetter.size(); i++) {
2759                    final String packageName = mExpectingBetter.keyAt(i);
2760                    if (!mPackages.containsKey(packageName)) {
2761                        final File scanFile = mExpectingBetter.valueAt(i);
2762
2763                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2764                                + " but never showed up; reverting to system");
2765
2766                        int reparseFlags = mDefParseFlags;
2767                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2768                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2769                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2770                                    | PackageParser.PARSE_IS_PRIVILEGED;
2771                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2772                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2773                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2774                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2775                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2776                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2777                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2778                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2779                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2780                        } else {
2781                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2782                            continue;
2783                        }
2784
2785                        mSettings.enableSystemPackageLPw(packageName);
2786
2787                        try {
2788                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2789                        } catch (PackageManagerException e) {
2790                            Slog.e(TAG, "Failed to parse original system package: "
2791                                    + e.getMessage());
2792                        }
2793                    }
2794                }
2795                final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime;
2796                final int dataPackagesCount = mPackages.size() - systemPackagesCount;
2797                Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime
2798                        + " ms, packageCount: " + dataPackagesCount
2799                        + " ms, timePerPackage: "
2800                        + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount));
2801                if (mIsUpgrade && dataPackagesCount > 0) {
2802                    MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time",
2803                            ((int) dataScanTime) / dataPackagesCount);
2804                }
2805            }
2806            mExpectingBetter.clear();
2807
2808            // Resolve the storage manager.
2809            mStorageManagerPackage = getStorageManagerPackageName();
2810
2811            // Resolve protected action filters. Only the setup wizard is allowed to
2812            // have a high priority filter for these actions.
2813            mSetupWizardPackage = getSetupWizardPackageName();
2814            if (mProtectedFilters.size() > 0) {
2815                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2816                    Slog.i(TAG, "No setup wizard;"
2817                        + " All protected intents capped to priority 0");
2818                }
2819                for (ActivityIntentInfo filter : mProtectedFilters) {
2820                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2821                        if (DEBUG_FILTERS) {
2822                            Slog.i(TAG, "Found setup wizard;"
2823                                + " allow priority " + filter.getPriority() + ";"
2824                                + " package: " + filter.activity.info.packageName
2825                                + " activity: " + filter.activity.className
2826                                + " priority: " + filter.getPriority());
2827                        }
2828                        // skip setup wizard; allow it to keep the high priority filter
2829                        continue;
2830                    }
2831                    if (DEBUG_FILTERS) {
2832                        Slog.i(TAG, "Protected action; cap priority to 0;"
2833                                + " package: " + filter.activity.info.packageName
2834                                + " activity: " + filter.activity.className
2835                                + " origPrio: " + filter.getPriority());
2836                    }
2837                    filter.setPriority(0);
2838                }
2839            }
2840            mDeferProtectedFilters = false;
2841            mProtectedFilters.clear();
2842
2843            // Now that we know all of the shared libraries, update all clients to have
2844            // the correct library paths.
2845            updateAllSharedLibrariesLPw(null);
2846
2847            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2848                // NOTE: We ignore potential failures here during a system scan (like
2849                // the rest of the commands above) because there's precious little we
2850                // can do about it. A settings error is reported, though.
2851                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2852            }
2853
2854            // Now that we know all the packages we are keeping,
2855            // read and update their last usage times.
2856            mPackageUsage.read(mPackages);
2857            mCompilerStats.read();
2858
2859            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2860                    SystemClock.uptimeMillis());
2861            Slog.i(TAG, "Time to scan packages: "
2862                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2863                    + " seconds");
2864
2865            // If the platform SDK has changed since the last time we booted,
2866            // we need to re-grant app permission to catch any new ones that
2867            // appear.  This is really a hack, and means that apps can in some
2868            // cases get permissions that the user didn't initially explicitly
2869            // allow...  it would be nice to have some better way to handle
2870            // this situation.
2871            int updateFlags = UPDATE_PERMISSIONS_ALL;
2872            if (ver.sdkVersion != mSdkVersion) {
2873                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2874                        + mSdkVersion + "; regranting permissions for internal storage");
2875                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2876            }
2877            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2878            ver.sdkVersion = mSdkVersion;
2879
2880            // If this is the first boot or an update from pre-M, and it is a normal
2881            // boot, then we need to initialize the default preferred apps across
2882            // all defined users.
2883            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2884                for (UserInfo user : sUserManager.getUsers(true)) {
2885                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2886                    applyFactoryDefaultBrowserLPw(user.id);
2887                    primeDomainVerificationsLPw(user.id);
2888                }
2889            }
2890
2891            // Prepare storage for system user really early during boot,
2892            // since core system apps like SettingsProvider and SystemUI
2893            // can't wait for user to start
2894            final int storageFlags;
2895            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2896                storageFlags = StorageManager.FLAG_STORAGE_DE;
2897            } else {
2898                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2899            }
2900            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2901                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2902                    true /* onlyCoreApps */);
2903            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2904                BootTimingsTraceLog traceLog = new BootTimingsTraceLog("SystemServerTimingAsync",
2905                        Trace.TRACE_TAG_PACKAGE_MANAGER);
2906                traceLog.traceBegin("AppDataFixup");
2907                try {
2908                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
2909                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2910                } catch (InstallerException e) {
2911                    Slog.w(TAG, "Trouble fixing GIDs", e);
2912                }
2913                traceLog.traceEnd();
2914
2915                traceLog.traceBegin("AppDataPrepare");
2916                if (deferPackages == null || deferPackages.isEmpty()) {
2917                    return;
2918                }
2919                int count = 0;
2920                for (String pkgName : deferPackages) {
2921                    PackageParser.Package pkg = null;
2922                    synchronized (mPackages) {
2923                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
2924                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
2925                            pkg = ps.pkg;
2926                        }
2927                    }
2928                    if (pkg != null) {
2929                        synchronized (mInstallLock) {
2930                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
2931                                    true /* maybeMigrateAppData */);
2932                        }
2933                        count++;
2934                    }
2935                }
2936                traceLog.traceEnd();
2937                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
2938            }, "prepareAppData");
2939
2940            // If this is first boot after an OTA, and a normal boot, then
2941            // we need to clear code cache directories.
2942            // Note that we do *not* clear the application profiles. These remain valid
2943            // across OTAs and are used to drive profile verification (post OTA) and
2944            // profile compilation (without waiting to collect a fresh set of profiles).
2945            if (mIsUpgrade && !onlyCore) {
2946                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2947                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2948                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2949                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2950                        // No apps are running this early, so no need to freeze
2951                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2952                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2953                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2954                    }
2955                }
2956                ver.fingerprint = Build.FINGERPRINT;
2957            }
2958
2959            checkDefaultBrowser();
2960
2961            // clear only after permissions and other defaults have been updated
2962            mExistingSystemPackages.clear();
2963            mPromoteSystemApps = false;
2964
2965            // All the changes are done during package scanning.
2966            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2967
2968            // can downgrade to reader
2969            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
2970            mSettings.writeLPr();
2971            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2972            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2973                    SystemClock.uptimeMillis());
2974
2975            if (!mOnlyCore) {
2976                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2977                mRequiredInstallerPackage = getRequiredInstallerLPr();
2978                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2979                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2980                if (mIntentFilterVerifierComponent != null) {
2981                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2982                            mIntentFilterVerifierComponent);
2983                } else {
2984                    mIntentFilterVerifier = null;
2985                }
2986                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2987                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
2988                        SharedLibraryInfo.VERSION_UNDEFINED);
2989                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2990                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
2991                        SharedLibraryInfo.VERSION_UNDEFINED);
2992            } else {
2993                mRequiredVerifierPackage = null;
2994                mRequiredInstallerPackage = null;
2995                mRequiredUninstallerPackage = null;
2996                mIntentFilterVerifierComponent = null;
2997                mIntentFilterVerifier = null;
2998                mServicesSystemSharedLibraryPackageName = null;
2999                mSharedSystemSharedLibraryPackageName = null;
3000            }
3001
3002            mInstallerService = new PackageInstallerService(context, this);
3003            final Pair<ComponentName, String> instantAppResolverComponent =
3004                    getInstantAppResolverLPr();
3005            if (instantAppResolverComponent != null) {
3006                if (DEBUG_EPHEMERAL) {
3007                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
3008                }
3009                mInstantAppResolverConnection = new EphemeralResolverConnection(
3010                        mContext, instantAppResolverComponent.first,
3011                        instantAppResolverComponent.second);
3012                mInstantAppResolverSettingsComponent =
3013                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
3014            } else {
3015                mInstantAppResolverConnection = null;
3016                mInstantAppResolverSettingsComponent = null;
3017            }
3018            updateInstantAppInstallerLocked(null);
3019
3020            // Read and update the usage of dex files.
3021            // Do this at the end of PM init so that all the packages have their
3022            // data directory reconciled.
3023            // At this point we know the code paths of the packages, so we can validate
3024            // the disk file and build the internal cache.
3025            // The usage file is expected to be small so loading and verifying it
3026            // should take a fairly small time compare to the other activities (e.g. package
3027            // scanning).
3028            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3029            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3030            for (int userId : currentUserIds) {
3031                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3032            }
3033            mDexManager.load(userPackages);
3034            if (mIsUpgrade) {
3035                MetricsLogger.histogram(null, "ota_package_manager_init_time",
3036                        (int) (SystemClock.uptimeMillis() - startTime));
3037            }
3038        } // synchronized (mPackages)
3039        } // synchronized (mInstallLock)
3040
3041        // Now after opening every single application zip, make sure they
3042        // are all flushed.  Not really needed, but keeps things nice and
3043        // tidy.
3044        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3045        Runtime.getRuntime().gc();
3046        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3047
3048        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3049        FallbackCategoryProvider.loadFallbacks();
3050        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3051
3052        // The initial scanning above does many calls into installd while
3053        // holding the mPackages lock, but we're mostly interested in yelling
3054        // once we have a booted system.
3055        mInstaller.setWarnIfHeld(mPackages);
3056
3057        // Expose private service for system components to use.
3058        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
3059        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3060    }
3061
3062    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3063        // we're only interested in updating the installer appliction when 1) it's not
3064        // already set or 2) the modified package is the installer
3065        if (mInstantAppInstallerActivity != null
3066                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3067                        .equals(modifiedPackage)) {
3068            return;
3069        }
3070        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3071    }
3072
3073    private static File preparePackageParserCache(boolean isUpgrade) {
3074        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3075            return null;
3076        }
3077
3078        // Disable package parsing on eng builds to allow for faster incremental development.
3079        if (Build.IS_ENG) {
3080            return null;
3081        }
3082
3083        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3084            Slog.i(TAG, "Disabling package parser cache due to system property.");
3085            return null;
3086        }
3087
3088        // The base directory for the package parser cache lives under /data/system/.
3089        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3090                "package_cache");
3091        if (cacheBaseDir == null) {
3092            return null;
3093        }
3094
3095        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3096        // This also serves to "GC" unused entries when the package cache version changes (which
3097        // can only happen during upgrades).
3098        if (isUpgrade) {
3099            FileUtils.deleteContents(cacheBaseDir);
3100        }
3101
3102
3103        // Return the versioned package cache directory. This is something like
3104        // "/data/system/package_cache/1"
3105        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3106
3107        // The following is a workaround to aid development on non-numbered userdebug
3108        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3109        // the system partition is newer.
3110        //
3111        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3112        // that starts with "eng." to signify that this is an engineering build and not
3113        // destined for release.
3114        if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3115            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3116
3117            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3118            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3119            // in general and should not be used for production changes. In this specific case,
3120            // we know that they will work.
3121            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3122            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3123                FileUtils.deleteContents(cacheBaseDir);
3124                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3125            }
3126        }
3127
3128        return cacheDir;
3129    }
3130
3131    @Override
3132    public boolean isFirstBoot() {
3133        // allow instant applications
3134        return mFirstBoot;
3135    }
3136
3137    @Override
3138    public boolean isOnlyCoreApps() {
3139        // allow instant applications
3140        return mOnlyCore;
3141    }
3142
3143    @Override
3144    public boolean isUpgrade() {
3145        // allow instant applications
3146        return mIsUpgrade;
3147    }
3148
3149    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3150        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3151
3152        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3153                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3154                UserHandle.USER_SYSTEM);
3155        if (matches.size() == 1) {
3156            return matches.get(0).getComponentInfo().packageName;
3157        } else if (matches.size() == 0) {
3158            Log.e(TAG, "There should probably be a verifier, but, none were found");
3159            return null;
3160        }
3161        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3162    }
3163
3164    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3165        synchronized (mPackages) {
3166            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3167            if (libraryEntry == null) {
3168                throw new IllegalStateException("Missing required shared library:" + name);
3169            }
3170            return libraryEntry.apk;
3171        }
3172    }
3173
3174    private @NonNull String getRequiredInstallerLPr() {
3175        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3176        intent.addCategory(Intent.CATEGORY_DEFAULT);
3177        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3178
3179        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3180                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3181                UserHandle.USER_SYSTEM);
3182        if (matches.size() == 1) {
3183            ResolveInfo resolveInfo = matches.get(0);
3184            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3185                throw new RuntimeException("The installer must be a privileged app");
3186            }
3187            return matches.get(0).getComponentInfo().packageName;
3188        } else {
3189            throw new RuntimeException("There must be exactly one installer; found " + matches);
3190        }
3191    }
3192
3193    private @NonNull String getRequiredUninstallerLPr() {
3194        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3195        intent.addCategory(Intent.CATEGORY_DEFAULT);
3196        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3197
3198        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3199                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3200                UserHandle.USER_SYSTEM);
3201        if (resolveInfo == null ||
3202                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3203            throw new RuntimeException("There must be exactly one uninstaller; found "
3204                    + resolveInfo);
3205        }
3206        return resolveInfo.getComponentInfo().packageName;
3207    }
3208
3209    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3210        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3211
3212        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3213                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3214                UserHandle.USER_SYSTEM);
3215        ResolveInfo best = null;
3216        final int N = matches.size();
3217        for (int i = 0; i < N; i++) {
3218            final ResolveInfo cur = matches.get(i);
3219            final String packageName = cur.getComponentInfo().packageName;
3220            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3221                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3222                continue;
3223            }
3224
3225            if (best == null || cur.priority > best.priority) {
3226                best = cur;
3227            }
3228        }
3229
3230        if (best != null) {
3231            return best.getComponentInfo().getComponentName();
3232        }
3233        Slog.w(TAG, "Intent filter verifier not found");
3234        return null;
3235    }
3236
3237    @Override
3238    public @Nullable ComponentName getInstantAppResolverComponent() {
3239        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3240            return null;
3241        }
3242        synchronized (mPackages) {
3243            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3244            if (instantAppResolver == null) {
3245                return null;
3246            }
3247            return instantAppResolver.first;
3248        }
3249    }
3250
3251    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3252        final String[] packageArray =
3253                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3254        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3255            if (DEBUG_EPHEMERAL) {
3256                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3257            }
3258            return null;
3259        }
3260
3261        final int callingUid = Binder.getCallingUid();
3262        final int resolveFlags =
3263                MATCH_DIRECT_BOOT_AWARE
3264                | MATCH_DIRECT_BOOT_UNAWARE
3265                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3266        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3267        final Intent resolverIntent = new Intent(actionName);
3268        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3269                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3270        // temporarily look for the old action
3271        if (resolvers.size() == 0) {
3272            if (DEBUG_EPHEMERAL) {
3273                Slog.d(TAG, "Ephemeral resolver not found with new action; try old one");
3274            }
3275            actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE;
3276            resolverIntent.setAction(actionName);
3277            resolvers = queryIntentServicesInternal(resolverIntent, null,
3278                    resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3279        }
3280        final int N = resolvers.size();
3281        if (N == 0) {
3282            if (DEBUG_EPHEMERAL) {
3283                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3284            }
3285            return null;
3286        }
3287
3288        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3289        for (int i = 0; i < N; i++) {
3290            final ResolveInfo info = resolvers.get(i);
3291
3292            if (info.serviceInfo == null) {
3293                continue;
3294            }
3295
3296            final String packageName = info.serviceInfo.packageName;
3297            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3298                if (DEBUG_EPHEMERAL) {
3299                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3300                            + " pkg: " + packageName + ", info:" + info);
3301                }
3302                continue;
3303            }
3304
3305            if (DEBUG_EPHEMERAL) {
3306                Slog.v(TAG, "Ephemeral resolver found;"
3307                        + " pkg: " + packageName + ", info:" + info);
3308            }
3309            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3310        }
3311        if (DEBUG_EPHEMERAL) {
3312            Slog.v(TAG, "Ephemeral resolver NOT found");
3313        }
3314        return null;
3315    }
3316
3317    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3318        final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE);
3319        intent.addCategory(Intent.CATEGORY_DEFAULT);
3320        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3321
3322        final int resolveFlags =
3323                MATCH_DIRECT_BOOT_AWARE
3324                | MATCH_DIRECT_BOOT_UNAWARE
3325                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3326        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3327                resolveFlags, UserHandle.USER_SYSTEM);
3328        // temporarily look for the old action
3329        if (matches.isEmpty()) {
3330            if (DEBUG_EPHEMERAL) {
3331                Slog.d(TAG, "Ephemeral installer not found with new action; try old one");
3332            }
3333            intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3334            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3335                    resolveFlags, UserHandle.USER_SYSTEM);
3336        }
3337        Iterator<ResolveInfo> iter = matches.iterator();
3338        while (iter.hasNext()) {
3339            final ResolveInfo rInfo = iter.next();
3340            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3341            if (ps != null) {
3342                final PermissionsState permissionsState = ps.getPermissionsState();
3343                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3344                    continue;
3345                }
3346            }
3347            iter.remove();
3348        }
3349        if (matches.size() == 0) {
3350            return null;
3351        } else if (matches.size() == 1) {
3352            return (ActivityInfo) matches.get(0).getComponentInfo();
3353        } else {
3354            throw new RuntimeException(
3355                    "There must be at most one ephemeral installer; found " + matches);
3356        }
3357    }
3358
3359    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3360            @NonNull ComponentName resolver) {
3361        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3362                .addCategory(Intent.CATEGORY_DEFAULT)
3363                .setPackage(resolver.getPackageName());
3364        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3365        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3366                UserHandle.USER_SYSTEM);
3367        // temporarily look for the old action
3368        if (matches.isEmpty()) {
3369            if (DEBUG_EPHEMERAL) {
3370                Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one");
3371            }
3372            intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS);
3373            matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3374                    UserHandle.USER_SYSTEM);
3375        }
3376        if (matches.isEmpty()) {
3377            return null;
3378        }
3379        return matches.get(0).getComponentInfo().getComponentName();
3380    }
3381
3382    private void primeDomainVerificationsLPw(int userId) {
3383        if (DEBUG_DOMAIN_VERIFICATION) {
3384            Slog.d(TAG, "Priming domain verifications in user " + userId);
3385        }
3386
3387        SystemConfig systemConfig = SystemConfig.getInstance();
3388        ArraySet<String> packages = systemConfig.getLinkedApps();
3389
3390        for (String packageName : packages) {
3391            PackageParser.Package pkg = mPackages.get(packageName);
3392            if (pkg != null) {
3393                if (!pkg.isSystemApp()) {
3394                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3395                    continue;
3396                }
3397
3398                ArraySet<String> domains = null;
3399                for (PackageParser.Activity a : pkg.activities) {
3400                    for (ActivityIntentInfo filter : a.intents) {
3401                        if (hasValidDomains(filter)) {
3402                            if (domains == null) {
3403                                domains = new ArraySet<String>();
3404                            }
3405                            domains.addAll(filter.getHostsList());
3406                        }
3407                    }
3408                }
3409
3410                if (domains != null && domains.size() > 0) {
3411                    if (DEBUG_DOMAIN_VERIFICATION) {
3412                        Slog.v(TAG, "      + " + packageName);
3413                    }
3414                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3415                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3416                    // and then 'always' in the per-user state actually used for intent resolution.
3417                    final IntentFilterVerificationInfo ivi;
3418                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3419                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3420                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3421                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3422                } else {
3423                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3424                            + "' does not handle web links");
3425                }
3426            } else {
3427                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3428            }
3429        }
3430
3431        scheduleWritePackageRestrictionsLocked(userId);
3432        scheduleWriteSettingsLocked();
3433    }
3434
3435    private void applyFactoryDefaultBrowserLPw(int userId) {
3436        // The default browser app's package name is stored in a string resource,
3437        // with a product-specific overlay used for vendor customization.
3438        String browserPkg = mContext.getResources().getString(
3439                com.android.internal.R.string.default_browser);
3440        if (!TextUtils.isEmpty(browserPkg)) {
3441            // non-empty string => required to be a known package
3442            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3443            if (ps == null) {
3444                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3445                browserPkg = null;
3446            } else {
3447                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3448            }
3449        }
3450
3451        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3452        // default.  If there's more than one, just leave everything alone.
3453        if (browserPkg == null) {
3454            calculateDefaultBrowserLPw(userId);
3455        }
3456    }
3457
3458    private void calculateDefaultBrowserLPw(int userId) {
3459        List<String> allBrowsers = resolveAllBrowserApps(userId);
3460        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3461        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3462    }
3463
3464    private List<String> resolveAllBrowserApps(int userId) {
3465        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3466        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3467                PackageManager.MATCH_ALL, userId);
3468
3469        final int count = list.size();
3470        List<String> result = new ArrayList<String>(count);
3471        for (int i=0; i<count; i++) {
3472            ResolveInfo info = list.get(i);
3473            if (info.activityInfo == null
3474                    || !info.handleAllWebDataURI
3475                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3476                    || result.contains(info.activityInfo.packageName)) {
3477                continue;
3478            }
3479            result.add(info.activityInfo.packageName);
3480        }
3481
3482        return result;
3483    }
3484
3485    private boolean packageIsBrowser(String packageName, int userId) {
3486        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3487                PackageManager.MATCH_ALL, userId);
3488        final int N = list.size();
3489        for (int i = 0; i < N; i++) {
3490            ResolveInfo info = list.get(i);
3491            if (packageName.equals(info.activityInfo.packageName)) {
3492                return true;
3493            }
3494        }
3495        return false;
3496    }
3497
3498    private void checkDefaultBrowser() {
3499        final int myUserId = UserHandle.myUserId();
3500        final String packageName = getDefaultBrowserPackageName(myUserId);
3501        if (packageName != null) {
3502            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3503            if (info == null) {
3504                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3505                synchronized (mPackages) {
3506                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3507                }
3508            }
3509        }
3510    }
3511
3512    @Override
3513    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3514            throws RemoteException {
3515        try {
3516            return super.onTransact(code, data, reply, flags);
3517        } catch (RuntimeException e) {
3518            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3519                Slog.wtf(TAG, "Package Manager Crash", e);
3520            }
3521            throw e;
3522        }
3523    }
3524
3525    static int[] appendInts(int[] cur, int[] add) {
3526        if (add == null) return cur;
3527        if (cur == null) return add;
3528        final int N = add.length;
3529        for (int i=0; i<N; i++) {
3530            cur = appendInt(cur, add[i]);
3531        }
3532        return cur;
3533    }
3534
3535    /**
3536     * Returns whether or not a full application can see an instant application.
3537     * <p>
3538     * Currently, there are three cases in which this can occur:
3539     * <ol>
3540     * <li>The calling application is a "special" process. The special
3541     *     processes are {@link Process#SYSTEM_UID}, {@link Process#SHELL_UID}
3542     *     and {@code 0}</li>
3543     * <li>The calling application has the permission
3544     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}</li>
3545     * <li>The calling application is the default launcher on the
3546     *     system partition.</li>
3547     * </ol>
3548     */
3549    private boolean canViewInstantApps(int callingUid, int userId) {
3550        if (callingUid == Process.SYSTEM_UID
3551                || callingUid == Process.SHELL_UID
3552                || callingUid == Process.ROOT_UID) {
3553            return true;
3554        }
3555        if (mContext.checkCallingOrSelfPermission(
3556                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3557            return true;
3558        }
3559        if (mContext.checkCallingOrSelfPermission(
3560                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3561            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3562            if (homeComponent != null
3563                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3564                return true;
3565            }
3566        }
3567        return false;
3568    }
3569
3570    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3571        if (!sUserManager.exists(userId)) return null;
3572        if (ps == null) {
3573            return null;
3574        }
3575        PackageParser.Package p = ps.pkg;
3576        if (p == null) {
3577            return null;
3578        }
3579        final int callingUid = Binder.getCallingUid();
3580        // Filter out ephemeral app metadata:
3581        //   * The system/shell/root can see metadata for any app
3582        //   * An installed app can see metadata for 1) other installed apps
3583        //     and 2) ephemeral apps that have explicitly interacted with it
3584        //   * Ephemeral apps can only see their own data and exposed installed apps
3585        //   * Holding a signature permission allows seeing instant apps
3586        if (filterAppAccessLPr(ps, callingUid, userId)) {
3587            return null;
3588        }
3589
3590        final PermissionsState permissionsState = ps.getPermissionsState();
3591
3592        // Compute GIDs only if requested
3593        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3594                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3595        // Compute granted permissions only if package has requested permissions
3596        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3597                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3598        final PackageUserState state = ps.readUserState(userId);
3599
3600        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3601                && ps.isSystem()) {
3602            flags |= MATCH_ANY_USER;
3603        }
3604
3605        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3606                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3607
3608        if (packageInfo == null) {
3609            return null;
3610        }
3611
3612        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3613                resolveExternalPackageNameLPr(p);
3614
3615        return packageInfo;
3616    }
3617
3618    @Override
3619    public void checkPackageStartable(String packageName, int userId) {
3620        final int callingUid = Binder.getCallingUid();
3621        if (getInstantAppPackageName(callingUid) != null) {
3622            throw new SecurityException("Instant applications don't have access to this method");
3623        }
3624        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3625        synchronized (mPackages) {
3626            final PackageSetting ps = mSettings.mPackages.get(packageName);
3627            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3628                throw new SecurityException("Package " + packageName + " was not found!");
3629            }
3630
3631            if (!ps.getInstalled(userId)) {
3632                throw new SecurityException(
3633                        "Package " + packageName + " was not installed for user " + userId + "!");
3634            }
3635
3636            if (mSafeMode && !ps.isSystem()) {
3637                throw new SecurityException("Package " + packageName + " not a system app!");
3638            }
3639
3640            if (mFrozenPackages.contains(packageName)) {
3641                throw new SecurityException("Package " + packageName + " is currently frozen!");
3642            }
3643
3644            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3645                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3646                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3647            }
3648        }
3649    }
3650
3651    @Override
3652    public boolean isPackageAvailable(String packageName, int userId) {
3653        if (!sUserManager.exists(userId)) return false;
3654        final int callingUid = Binder.getCallingUid();
3655        enforceCrossUserPermission(callingUid, userId,
3656                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
3657        synchronized (mPackages) {
3658            PackageParser.Package p = mPackages.get(packageName);
3659            if (p != null) {
3660                final PackageSetting ps = (PackageSetting) p.mExtras;
3661                if (filterAppAccessLPr(ps, callingUid, userId)) {
3662                    return false;
3663                }
3664                if (ps != null) {
3665                    final PackageUserState state = ps.readUserState(userId);
3666                    if (state != null) {
3667                        return PackageParser.isAvailable(state);
3668                    }
3669                }
3670            }
3671        }
3672        return false;
3673    }
3674
3675    @Override
3676    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3677        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3678                flags, Binder.getCallingUid(), userId);
3679    }
3680
3681    @Override
3682    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3683            int flags, int userId) {
3684        return getPackageInfoInternal(versionedPackage.getPackageName(),
3685                versionedPackage.getVersionCode(), flags, Binder.getCallingUid(), userId);
3686    }
3687
3688    /**
3689     * Important: The provided filterCallingUid is used exclusively to filter out packages
3690     * that can be seen based on user state. It's typically the original caller uid prior
3691     * to clearing. Because it can only be provided by trusted code, it's value can be
3692     * trusted and will be used as-is; unlike userId which will be validated by this method.
3693     */
3694    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3695            int flags, int filterCallingUid, int userId) {
3696        if (!sUserManager.exists(userId)) return null;
3697        flags = updateFlagsForPackage(flags, userId, packageName);
3698        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3699                false /* requireFullPermission */, false /* checkShell */, "get package info");
3700
3701        // reader
3702        synchronized (mPackages) {
3703            // Normalize package name to handle renamed packages and static libs
3704            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3705
3706            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3707            if (matchFactoryOnly) {
3708                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3709                if (ps != null) {
3710                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3711                        return null;
3712                    }
3713                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3714                        return null;
3715                    }
3716                    return generatePackageInfo(ps, flags, userId);
3717                }
3718            }
3719
3720            PackageParser.Package p = mPackages.get(packageName);
3721            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3722                return null;
3723            }
3724            if (DEBUG_PACKAGE_INFO)
3725                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3726            if (p != null) {
3727                final PackageSetting ps = (PackageSetting) p.mExtras;
3728                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3729                    return null;
3730                }
3731                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
3732                    return null;
3733                }
3734                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3735            }
3736            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3737                final PackageSetting ps = mSettings.mPackages.get(packageName);
3738                if (ps == null) return null;
3739                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3740                    return null;
3741                }
3742                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3743                    return null;
3744                }
3745                return generatePackageInfo(ps, flags, userId);
3746            }
3747        }
3748        return null;
3749    }
3750
3751    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
3752        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
3753            return true;
3754        }
3755        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
3756            return true;
3757        }
3758        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
3759            return true;
3760        }
3761        return false;
3762    }
3763
3764    private boolean isComponentVisibleToInstantApp(
3765            @Nullable ComponentName component, @ComponentType int type) {
3766        if (type == TYPE_ACTIVITY) {
3767            final PackageParser.Activity activity = mActivities.mActivities.get(component);
3768            return activity != null
3769                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3770                    : false;
3771        } else if (type == TYPE_RECEIVER) {
3772            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
3773            return activity != null
3774                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3775                    : false;
3776        } else if (type == TYPE_SERVICE) {
3777            final PackageParser.Service service = mServices.mServices.get(component);
3778            return service != null
3779                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3780                    : false;
3781        } else if (type == TYPE_PROVIDER) {
3782            final PackageParser.Provider provider = mProviders.mProviders.get(component);
3783            return provider != null
3784                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3785                    : false;
3786        } else if (type == TYPE_UNKNOWN) {
3787            return isComponentVisibleToInstantApp(component);
3788        }
3789        return false;
3790    }
3791
3792    /**
3793     * Returns whether or not access to the application should be filtered.
3794     * <p>
3795     * Access may be limited based upon whether the calling or target applications
3796     * are instant applications.
3797     *
3798     * @see #canAccessInstantApps(int)
3799     */
3800    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
3801            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
3802        // if we're in an isolated process, get the real calling UID
3803        if (Process.isIsolated(callingUid)) {
3804            callingUid = mIsolatedOwners.get(callingUid);
3805        }
3806        final String instantAppPkgName = getInstantAppPackageName(callingUid);
3807        final boolean callerIsInstantApp = instantAppPkgName != null;
3808        if (ps == null) {
3809            if (callerIsInstantApp) {
3810                // pretend the application exists, but, needs to be filtered
3811                return true;
3812            }
3813            return false;
3814        }
3815        // if the target and caller are the same application, don't filter
3816        if (isCallerSameApp(ps.name, callingUid)) {
3817            return false;
3818        }
3819        if (callerIsInstantApp) {
3820            // request for a specific component; if it hasn't been explicitly exposed, filter
3821            if (component != null) {
3822                return !isComponentVisibleToInstantApp(component, componentType);
3823            }
3824            // request for application; if no components have been explicitly exposed, filter
3825            return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps;
3826        }
3827        if (ps.getInstantApp(userId)) {
3828            // caller can see all components of all instant applications, don't filter
3829            if (canViewInstantApps(callingUid, userId)) {
3830                return false;
3831            }
3832            // request for a specific instant application component, filter
3833            if (component != null) {
3834                return true;
3835            }
3836            // request for an instant application; if the caller hasn't been granted access, filter
3837            return !mInstantAppRegistry.isInstantAccessGranted(
3838                    userId, UserHandle.getAppId(callingUid), ps.appId);
3839        }
3840        return false;
3841    }
3842
3843    /**
3844     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
3845     */
3846    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
3847        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
3848    }
3849
3850    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
3851            int flags) {
3852        // Callers can access only the libs they depend on, otherwise they need to explicitly
3853        // ask for the shared libraries given the caller is allowed to access all static libs.
3854        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
3855            // System/shell/root get to see all static libs
3856            final int appId = UserHandle.getAppId(uid);
3857            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
3858                    || appId == Process.ROOT_UID) {
3859                return false;
3860            }
3861        }
3862
3863        // No package means no static lib as it is always on internal storage
3864        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
3865            return false;
3866        }
3867
3868        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
3869                ps.pkg.staticSharedLibVersion);
3870        if (libEntry == null) {
3871            return false;
3872        }
3873
3874        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
3875        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
3876        if (uidPackageNames == null) {
3877            return true;
3878        }
3879
3880        for (String uidPackageName : uidPackageNames) {
3881            if (ps.name.equals(uidPackageName)) {
3882                return false;
3883            }
3884            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
3885            if (uidPs != null) {
3886                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
3887                        libEntry.info.getName());
3888                if (index < 0) {
3889                    continue;
3890                }
3891                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
3892                    return false;
3893                }
3894            }
3895        }
3896        return true;
3897    }
3898
3899    @Override
3900    public String[] currentToCanonicalPackageNames(String[] names) {
3901        final int callingUid = Binder.getCallingUid();
3902        if (getInstantAppPackageName(callingUid) != null) {
3903            return names;
3904        }
3905        final String[] out = new String[names.length];
3906        // reader
3907        synchronized (mPackages) {
3908            final int callingUserId = UserHandle.getUserId(callingUid);
3909            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
3910            for (int i=names.length-1; i>=0; i--) {
3911                final PackageSetting ps = mSettings.mPackages.get(names[i]);
3912                boolean translateName = false;
3913                if (ps != null && ps.realName != null) {
3914                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
3915                    translateName = !targetIsInstantApp
3916                            || canViewInstantApps
3917                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
3918                                    UserHandle.getAppId(callingUid), ps.appId);
3919                }
3920                out[i] = translateName ? ps.realName : names[i];
3921            }
3922        }
3923        return out;
3924    }
3925
3926    @Override
3927    public String[] canonicalToCurrentPackageNames(String[] names) {
3928        final int callingUid = Binder.getCallingUid();
3929        if (getInstantAppPackageName(callingUid) != null) {
3930            return names;
3931        }
3932        final String[] out = new String[names.length];
3933        // reader
3934        synchronized (mPackages) {
3935            final int callingUserId = UserHandle.getUserId(callingUid);
3936            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
3937            for (int i=names.length-1; i>=0; i--) {
3938                final String cur = mSettings.getRenamedPackageLPr(names[i]);
3939                boolean translateName = false;
3940                if (cur != null) {
3941                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
3942                    final boolean targetIsInstantApp =
3943                            ps != null && ps.getInstantApp(callingUserId);
3944                    translateName = !targetIsInstantApp
3945                            || canViewInstantApps
3946                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
3947                                    UserHandle.getAppId(callingUid), ps.appId);
3948                }
3949                out[i] = translateName ? cur : names[i];
3950            }
3951        }
3952        return out;
3953    }
3954
3955    @Override
3956    public int getPackageUid(String packageName, int flags, int userId) {
3957        if (!sUserManager.exists(userId)) return -1;
3958        final int callingUid = Binder.getCallingUid();
3959        flags = updateFlagsForPackage(flags, userId, packageName);
3960        enforceCrossUserPermission(callingUid, userId,
3961                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
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 -1;
3970                }
3971                return UserHandle.getUid(userId, p.applicationInfo.uid);
3972            }
3973            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3974                final PackageSetting ps = mSettings.mPackages.get(packageName);
3975                if (ps != null && ps.isMatch(flags)
3976                        && !filterAppAccessLPr(ps, callingUid, userId)) {
3977                    return UserHandle.getUid(userId, ps.appId);
3978                }
3979            }
3980        }
3981
3982        return -1;
3983    }
3984
3985    @Override
3986    public int[] getPackageGids(String packageName, int flags, int userId) {
3987        if (!sUserManager.exists(userId)) return null;
3988        final int callingUid = Binder.getCallingUid();
3989        flags = updateFlagsForPackage(flags, userId, packageName);
3990        enforceCrossUserPermission(callingUid, userId,
3991                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
3992
3993        // reader
3994        synchronized (mPackages) {
3995            final PackageParser.Package p = mPackages.get(packageName);
3996            if (p != null && p.isMatch(flags)) {
3997                PackageSetting ps = (PackageSetting) p.mExtras;
3998                if (filterAppAccessLPr(ps, callingUid, userId)) {
3999                    return null;
4000                }
4001                // TODO: Shouldn't this be checking for package installed state for userId and
4002                // return null?
4003                return ps.getPermissionsState().computeGids(userId);
4004            }
4005            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4006                final PackageSetting ps = mSettings.mPackages.get(packageName);
4007                if (ps != null && ps.isMatch(flags)
4008                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4009                    return ps.getPermissionsState().computeGids(userId);
4010                }
4011            }
4012        }
4013
4014        return null;
4015    }
4016
4017    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
4018        if (bp.perm != null) {
4019            return PackageParser.generatePermissionInfo(bp.perm, flags);
4020        }
4021        PermissionInfo pi = new PermissionInfo();
4022        pi.name = bp.name;
4023        pi.packageName = bp.sourcePackage;
4024        pi.nonLocalizedLabel = bp.name;
4025        pi.protectionLevel = bp.protectionLevel;
4026        return pi;
4027    }
4028
4029    @Override
4030    public PermissionInfo getPermissionInfo(String name, int flags) {
4031        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4032            return null;
4033        }
4034        // reader
4035        synchronized (mPackages) {
4036            final BasePermission p = mSettings.mPermissions.get(name);
4037            if (p != null) {
4038                return generatePermissionInfo(p, flags);
4039            }
4040            return null;
4041        }
4042    }
4043
4044    @Override
4045    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
4046            int flags) {
4047        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4048            return null;
4049        }
4050        // reader
4051        synchronized (mPackages) {
4052            if (group != null && !mPermissionGroups.containsKey(group)) {
4053                // This is thrown as NameNotFoundException
4054                return null;
4055            }
4056
4057            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
4058            for (BasePermission p : mSettings.mPermissions.values()) {
4059                if (group == null) {
4060                    if (p.perm == null || p.perm.info.group == null) {
4061                        out.add(generatePermissionInfo(p, flags));
4062                    }
4063                } else {
4064                    if (p.perm != null && group.equals(p.perm.info.group)) {
4065                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
4066                    }
4067                }
4068            }
4069            return new ParceledListSlice<>(out);
4070        }
4071    }
4072
4073    @Override
4074    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
4075        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4076            return null;
4077        }
4078        // reader
4079        synchronized (mPackages) {
4080            return PackageParser.generatePermissionGroupInfo(
4081                    mPermissionGroups.get(name), flags);
4082        }
4083    }
4084
4085    @Override
4086    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4087        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4088            return ParceledListSlice.emptyList();
4089        }
4090        // reader
4091        synchronized (mPackages) {
4092            final int N = mPermissionGroups.size();
4093            ArrayList<PermissionGroupInfo> out
4094                    = new ArrayList<PermissionGroupInfo>(N);
4095            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
4096                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
4097            }
4098            return new ParceledListSlice<>(out);
4099        }
4100    }
4101
4102    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4103            int filterCallingUid, int userId) {
4104        if (!sUserManager.exists(userId)) return null;
4105        PackageSetting ps = mSettings.mPackages.get(packageName);
4106        if (ps != null) {
4107            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4108                return null;
4109            }
4110            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4111                return null;
4112            }
4113            if (ps.pkg == null) {
4114                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4115                if (pInfo != null) {
4116                    return pInfo.applicationInfo;
4117                }
4118                return null;
4119            }
4120            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4121                    ps.readUserState(userId), userId);
4122            if (ai != null) {
4123                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4124            }
4125            return ai;
4126        }
4127        return null;
4128    }
4129
4130    @Override
4131    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4132        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4133    }
4134
4135    /**
4136     * Important: The provided filterCallingUid is used exclusively to filter out applications
4137     * that can be seen based on user state. It's typically the original caller uid prior
4138     * to clearing. Because it can only be provided by trusted code, it's value can be
4139     * trusted and will be used as-is; unlike userId which will be validated by this method.
4140     */
4141    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4142            int filterCallingUid, int userId) {
4143        if (!sUserManager.exists(userId)) return null;
4144        flags = updateFlagsForApplication(flags, userId, packageName);
4145        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4146                false /* requireFullPermission */, false /* checkShell */, "get application info");
4147
4148        // writer
4149        synchronized (mPackages) {
4150            // Normalize package name to handle renamed packages and static libs
4151            packageName = resolveInternalPackageNameLPr(packageName,
4152                    PackageManager.VERSION_CODE_HIGHEST);
4153
4154            PackageParser.Package p = mPackages.get(packageName);
4155            if (DEBUG_PACKAGE_INFO) Log.v(
4156                    TAG, "getApplicationInfo " + packageName
4157                    + ": " + p);
4158            if (p != null) {
4159                PackageSetting ps = mSettings.mPackages.get(packageName);
4160                if (ps == null) return null;
4161                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4162                    return null;
4163                }
4164                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4165                    return null;
4166                }
4167                // Note: isEnabledLP() does not apply here - always return info
4168                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4169                        p, flags, ps.readUserState(userId), userId);
4170                if (ai != null) {
4171                    ai.packageName = resolveExternalPackageNameLPr(p);
4172                }
4173                return ai;
4174            }
4175            if ("android".equals(packageName)||"system".equals(packageName)) {
4176                return mAndroidApplication;
4177            }
4178            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4179                // Already generates the external package name
4180                return generateApplicationInfoFromSettingsLPw(packageName,
4181                        flags, filterCallingUid, userId);
4182            }
4183        }
4184        return null;
4185    }
4186
4187    private String normalizePackageNameLPr(String packageName) {
4188        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4189        return normalizedPackageName != null ? normalizedPackageName : packageName;
4190    }
4191
4192    @Override
4193    public void deletePreloadsFileCache() {
4194        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4195            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4196        }
4197        File dir = Environment.getDataPreloadsFileCacheDirectory();
4198        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4199        FileUtils.deleteContents(dir);
4200    }
4201
4202    @Override
4203    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4204            final int storageFlags, final IPackageDataObserver observer) {
4205        mContext.enforceCallingOrSelfPermission(
4206                android.Manifest.permission.CLEAR_APP_CACHE, null);
4207        mHandler.post(() -> {
4208            boolean success = false;
4209            try {
4210                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4211                success = true;
4212            } catch (IOException e) {
4213                Slog.w(TAG, e);
4214            }
4215            if (observer != null) {
4216                try {
4217                    observer.onRemoveCompleted(null, success);
4218                } catch (RemoteException e) {
4219                    Slog.w(TAG, e);
4220                }
4221            }
4222        });
4223    }
4224
4225    @Override
4226    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4227            final int storageFlags, final IntentSender pi) {
4228        mContext.enforceCallingOrSelfPermission(
4229                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4230        mHandler.post(() -> {
4231            boolean success = false;
4232            try {
4233                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4234                success = true;
4235            } catch (IOException e) {
4236                Slog.w(TAG, e);
4237            }
4238            if (pi != null) {
4239                try {
4240                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4241                } catch (SendIntentException e) {
4242                    Slog.w(TAG, e);
4243                }
4244            }
4245        });
4246    }
4247
4248    /**
4249     * Blocking call to clear various types of cached data across the system
4250     * until the requested bytes are available.
4251     */
4252    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4253        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4254        final File file = storage.findPathForUuid(volumeUuid);
4255        if (file.getUsableSpace() >= bytes) return;
4256
4257        if (ENABLE_FREE_CACHE_V2) {
4258            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4259                    volumeUuid);
4260            final boolean aggressive = (storageFlags
4261                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4262            final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags);
4263
4264            // 1. Pre-flight to determine if we have any chance to succeed
4265            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4266            if (internalVolume && (aggressive || SystemProperties
4267                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4268                deletePreloadsFileCache();
4269                if (file.getUsableSpace() >= bytes) return;
4270            }
4271
4272            // 3. Consider parsed APK data (aggressive only)
4273            if (internalVolume && aggressive) {
4274                FileUtils.deleteContents(mCacheDir);
4275                if (file.getUsableSpace() >= bytes) return;
4276            }
4277
4278            // 4. Consider cached app data (above quotas)
4279            try {
4280                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4281                        Installer.FLAG_FREE_CACHE_V2);
4282            } catch (InstallerException ignored) {
4283            }
4284            if (file.getUsableSpace() >= bytes) return;
4285
4286            // 5. Consider shared libraries with refcount=0 and age>min cache period
4287            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4288                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4289                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4290                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4291                return;
4292            }
4293
4294            // 6. Consider dexopt output (aggressive only)
4295            // TODO: Implement
4296
4297            // 7. Consider installed instant apps unused longer than min cache period
4298            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4299                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4300                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4301                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4302                return;
4303            }
4304
4305            // 8. Consider cached app data (below quotas)
4306            try {
4307                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4308                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4309            } catch (InstallerException ignored) {
4310            }
4311            if (file.getUsableSpace() >= bytes) return;
4312
4313            // 9. Consider DropBox entries
4314            // TODO: Implement
4315
4316            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4317            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4318                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4319                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4320                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4321                return;
4322            }
4323        } else {
4324            try {
4325                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4326            } catch (InstallerException ignored) {
4327            }
4328            if (file.getUsableSpace() >= bytes) return;
4329        }
4330
4331        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4332    }
4333
4334    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4335            throws IOException {
4336        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4337        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4338
4339        List<VersionedPackage> packagesToDelete = null;
4340        final long now = System.currentTimeMillis();
4341
4342        synchronized (mPackages) {
4343            final int[] allUsers = sUserManager.getUserIds();
4344            final int libCount = mSharedLibraries.size();
4345            for (int i = 0; i < libCount; i++) {
4346                final SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4347                if (versionedLib == null) {
4348                    continue;
4349                }
4350                final int versionCount = versionedLib.size();
4351                for (int j = 0; j < versionCount; j++) {
4352                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4353                    // Skip packages that are not static shared libs.
4354                    if (!libInfo.isStatic()) {
4355                        break;
4356                    }
4357                    // Important: We skip static shared libs used for some user since
4358                    // in such a case we need to keep the APK on the device. The check for
4359                    // a lib being used for any user is performed by the uninstall call.
4360                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4361                    // Resolve the package name - we use synthetic package names internally
4362                    final String internalPackageName = resolveInternalPackageNameLPr(
4363                            declaringPackage.getPackageName(), declaringPackage.getVersionCode());
4364                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4365                    // Skip unused static shared libs cached less than the min period
4366                    // to prevent pruning a lib needed by a subsequently installed package.
4367                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4368                        continue;
4369                    }
4370                    if (packagesToDelete == null) {
4371                        packagesToDelete = new ArrayList<>();
4372                    }
4373                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4374                            declaringPackage.getVersionCode()));
4375                }
4376            }
4377        }
4378
4379        if (packagesToDelete != null) {
4380            final int packageCount = packagesToDelete.size();
4381            for (int i = 0; i < packageCount; i++) {
4382                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4383                // Delete the package synchronously (will fail of the lib used for any user).
4384                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getVersionCode(),
4385                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4386                                == PackageManager.DELETE_SUCCEEDED) {
4387                    if (volume.getUsableSpace() >= neededSpace) {
4388                        return true;
4389                    }
4390                }
4391            }
4392        }
4393
4394        return false;
4395    }
4396
4397    /**
4398     * Update given flags based on encryption status of current user.
4399     */
4400    private int updateFlags(int flags, int userId) {
4401        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4402                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4403            // Caller expressed an explicit opinion about what encryption
4404            // aware/unaware components they want to see, so fall through and
4405            // give them what they want
4406        } else {
4407            // Caller expressed no opinion, so match based on user state
4408            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4409                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4410            } else {
4411                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4412            }
4413        }
4414        return flags;
4415    }
4416
4417    private UserManagerInternal getUserManagerInternal() {
4418        if (mUserManagerInternal == null) {
4419            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4420        }
4421        return mUserManagerInternal;
4422    }
4423
4424    private DeviceIdleController.LocalService getDeviceIdleController() {
4425        if (mDeviceIdleController == null) {
4426            mDeviceIdleController =
4427                    LocalServices.getService(DeviceIdleController.LocalService.class);
4428        }
4429        return mDeviceIdleController;
4430    }
4431
4432    /**
4433     * Update given flags when being used to request {@link PackageInfo}.
4434     */
4435    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4436        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4437        boolean triaged = true;
4438        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4439                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4440            // Caller is asking for component details, so they'd better be
4441            // asking for specific encryption matching behavior, or be triaged
4442            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4443                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4444                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4445                triaged = false;
4446            }
4447        }
4448        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4449                | PackageManager.MATCH_SYSTEM_ONLY
4450                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4451            triaged = false;
4452        }
4453        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4454            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
4455                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4456                    + Debug.getCallers(5));
4457        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4458                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4459            // If the caller wants all packages and has a restricted profile associated with it,
4460            // then match all users. This is to make sure that launchers that need to access work
4461            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4462            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4463            flags |= PackageManager.MATCH_ANY_USER;
4464        }
4465        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4466            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4467                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4468        }
4469        return updateFlags(flags, userId);
4470    }
4471
4472    /**
4473     * Update given flags when being used to request {@link ApplicationInfo}.
4474     */
4475    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4476        return updateFlagsForPackage(flags, userId, cookie);
4477    }
4478
4479    /**
4480     * Update given flags when being used to request {@link ComponentInfo}.
4481     */
4482    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4483        if (cookie instanceof Intent) {
4484            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4485                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4486            }
4487        }
4488
4489        boolean triaged = true;
4490        // Caller is asking for component details, so they'd better be
4491        // asking for specific encryption matching behavior, or be triaged
4492        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4493                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4494                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4495            triaged = false;
4496        }
4497        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4498            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4499                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4500        }
4501
4502        return updateFlags(flags, userId);
4503    }
4504
4505    /**
4506     * Update given intent when being used to request {@link ResolveInfo}.
4507     */
4508    private Intent updateIntentForResolve(Intent intent) {
4509        if (intent.getSelector() != null) {
4510            intent = intent.getSelector();
4511        }
4512        if (DEBUG_PREFERRED) {
4513            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4514        }
4515        return intent;
4516    }
4517
4518    /**
4519     * Update given flags when being used to request {@link ResolveInfo}.
4520     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4521     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4522     * flag set. However, this flag is only honoured in three circumstances:
4523     * <ul>
4524     * <li>when called from a system process</li>
4525     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4526     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4527     * action and a {@code android.intent.category.BROWSABLE} category</li>
4528     * </ul>
4529     */
4530    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4531        return updateFlagsForResolve(flags, userId, intent, callingUid,
4532                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4533    }
4534    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4535            boolean wantInstantApps) {
4536        return updateFlagsForResolve(flags, userId, intent, callingUid,
4537                wantInstantApps, false /*onlyExposedExplicitly*/);
4538    }
4539    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4540            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4541        // Safe mode means we shouldn't match any third-party components
4542        if (mSafeMode) {
4543            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4544        }
4545        if (getInstantAppPackageName(callingUid) != null) {
4546            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4547            if (onlyExposedExplicitly) {
4548                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4549            }
4550            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4551            flags |= PackageManager.MATCH_INSTANT;
4552        } else {
4553            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4554            final boolean allowMatchInstant =
4555                    (wantInstantApps
4556                            && Intent.ACTION_VIEW.equals(intent.getAction())
4557                            && hasWebURI(intent))
4558                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4559            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4560                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4561            if (!allowMatchInstant) {
4562                flags &= ~PackageManager.MATCH_INSTANT;
4563            }
4564        }
4565        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4566    }
4567
4568    @Override
4569    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4570        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4571    }
4572
4573    /**
4574     * Important: The provided filterCallingUid is used exclusively to filter out activities
4575     * that can be seen based on user state. It's typically the original caller uid prior
4576     * to clearing. Because it can only be provided by trusted code, it's value can be
4577     * trusted and will be used as-is; unlike userId which will be validated by this method.
4578     */
4579    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4580            int filterCallingUid, int userId) {
4581        if (!sUserManager.exists(userId)) return null;
4582        flags = updateFlagsForComponent(flags, userId, component);
4583        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4584                false /* requireFullPermission */, false /* checkShell */, "get activity info");
4585        synchronized (mPackages) {
4586            PackageParser.Activity a = mActivities.mActivities.get(component);
4587
4588            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4589            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4590                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4591                if (ps == null) return null;
4592                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4593                    return null;
4594                }
4595                return PackageParser.generateActivityInfo(
4596                        a, flags, ps.readUserState(userId), userId);
4597            }
4598            if (mResolveComponentName.equals(component)) {
4599                return PackageParser.generateActivityInfo(
4600                        mResolveActivity, flags, new PackageUserState(), userId);
4601            }
4602        }
4603        return null;
4604    }
4605
4606    @Override
4607    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4608            String resolvedType) {
4609        synchronized (mPackages) {
4610            if (component.equals(mResolveComponentName)) {
4611                // The resolver supports EVERYTHING!
4612                return true;
4613            }
4614            final int callingUid = Binder.getCallingUid();
4615            final int callingUserId = UserHandle.getUserId(callingUid);
4616            PackageParser.Activity a = mActivities.mActivities.get(component);
4617            if (a == null) {
4618                return false;
4619            }
4620            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4621            if (ps == null) {
4622                return false;
4623            }
4624            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4625                return false;
4626            }
4627            for (int i=0; i<a.intents.size(); i++) {
4628                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4629                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4630                    return true;
4631                }
4632            }
4633            return false;
4634        }
4635    }
4636
4637    @Override
4638    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4639        if (!sUserManager.exists(userId)) return null;
4640        final int callingUid = Binder.getCallingUid();
4641        flags = updateFlagsForComponent(flags, userId, component);
4642        enforceCrossUserPermission(callingUid, userId,
4643                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4644        synchronized (mPackages) {
4645            PackageParser.Activity a = mReceivers.mActivities.get(component);
4646            if (DEBUG_PACKAGE_INFO) Log.v(
4647                TAG, "getReceiverInfo " + component + ": " + a);
4648            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4649                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4650                if (ps == null) return null;
4651                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4652                    return null;
4653                }
4654                return PackageParser.generateActivityInfo(
4655                        a, flags, ps.readUserState(userId), userId);
4656            }
4657        }
4658        return null;
4659    }
4660
4661    @Override
4662    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4663            int flags, int userId) {
4664        if (!sUserManager.exists(userId)) return null;
4665        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4666        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4667            return null;
4668        }
4669
4670        flags = updateFlagsForPackage(flags, userId, null);
4671
4672        final boolean canSeeStaticLibraries =
4673                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4674                        == PERMISSION_GRANTED
4675                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4676                        == PERMISSION_GRANTED
4677                || canRequestPackageInstallsInternal(packageName,
4678                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
4679                        false  /* throwIfPermNotDeclared*/)
4680                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4681                        == PERMISSION_GRANTED;
4682
4683        synchronized (mPackages) {
4684            List<SharedLibraryInfo> result = null;
4685
4686            final int libCount = mSharedLibraries.size();
4687            for (int i = 0; i < libCount; i++) {
4688                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4689                if (versionedLib == null) {
4690                    continue;
4691                }
4692
4693                final int versionCount = versionedLib.size();
4694                for (int j = 0; j < versionCount; j++) {
4695                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4696                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4697                        break;
4698                    }
4699                    final long identity = Binder.clearCallingIdentity();
4700                    try {
4701                        PackageInfo packageInfo = getPackageInfoVersioned(
4702                                libInfo.getDeclaringPackage(), flags
4703                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
4704                        if (packageInfo == null) {
4705                            continue;
4706                        }
4707                    } finally {
4708                        Binder.restoreCallingIdentity(identity);
4709                    }
4710
4711                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4712                            libInfo.getVersion(), libInfo.getType(),
4713                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
4714                            flags, userId));
4715
4716                    if (result == null) {
4717                        result = new ArrayList<>();
4718                    }
4719                    result.add(resLibInfo);
4720                }
4721            }
4722
4723            return result != null ? new ParceledListSlice<>(result) : null;
4724        }
4725    }
4726
4727    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4728            SharedLibraryInfo libInfo, int flags, int userId) {
4729        List<VersionedPackage> versionedPackages = null;
4730        final int packageCount = mSettings.mPackages.size();
4731        for (int i = 0; i < packageCount; i++) {
4732            PackageSetting ps = mSettings.mPackages.valueAt(i);
4733
4734            if (ps == null) {
4735                continue;
4736            }
4737
4738            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4739                continue;
4740            }
4741
4742            final String libName = libInfo.getName();
4743            if (libInfo.isStatic()) {
4744                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4745                if (libIdx < 0) {
4746                    continue;
4747                }
4748                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
4749                    continue;
4750                }
4751                if (versionedPackages == null) {
4752                    versionedPackages = new ArrayList<>();
4753                }
4754                // If the dependent is a static shared lib, use the public package name
4755                String dependentPackageName = ps.name;
4756                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4757                    dependentPackageName = ps.pkg.manifestPackageName;
4758                }
4759                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
4760            } else if (ps.pkg != null) {
4761                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
4762                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
4763                    if (versionedPackages == null) {
4764                        versionedPackages = new ArrayList<>();
4765                    }
4766                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
4767                }
4768            }
4769        }
4770
4771        return versionedPackages;
4772    }
4773
4774    @Override
4775    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
4776        if (!sUserManager.exists(userId)) return null;
4777        final int callingUid = Binder.getCallingUid();
4778        flags = updateFlagsForComponent(flags, userId, component);
4779        enforceCrossUserPermission(callingUid, userId,
4780                false /* requireFullPermission */, false /* checkShell */, "get service info");
4781        synchronized (mPackages) {
4782            PackageParser.Service s = mServices.mServices.get(component);
4783            if (DEBUG_PACKAGE_INFO) Log.v(
4784                TAG, "getServiceInfo " + component + ": " + s);
4785            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
4786                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4787                if (ps == null) return null;
4788                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
4789                    return null;
4790                }
4791                return PackageParser.generateServiceInfo(
4792                        s, flags, ps.readUserState(userId), userId);
4793            }
4794        }
4795        return null;
4796    }
4797
4798    @Override
4799    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
4800        if (!sUserManager.exists(userId)) return null;
4801        final int callingUid = Binder.getCallingUid();
4802        flags = updateFlagsForComponent(flags, userId, component);
4803        enforceCrossUserPermission(callingUid, userId,
4804                false /* requireFullPermission */, false /* checkShell */, "get provider info");
4805        synchronized (mPackages) {
4806            PackageParser.Provider p = mProviders.mProviders.get(component);
4807            if (DEBUG_PACKAGE_INFO) Log.v(
4808                TAG, "getProviderInfo " + component + ": " + p);
4809            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
4810                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4811                if (ps == null) return null;
4812                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
4813                    return null;
4814                }
4815                return PackageParser.generateProviderInfo(
4816                        p, flags, ps.readUserState(userId), userId);
4817            }
4818        }
4819        return null;
4820    }
4821
4822    @Override
4823    public String[] getSystemSharedLibraryNames() {
4824        // allow instant applications
4825        synchronized (mPackages) {
4826            Set<String> libs = null;
4827            final int libCount = mSharedLibraries.size();
4828            for (int i = 0; i < libCount; i++) {
4829                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4830                if (versionedLib == null) {
4831                    continue;
4832                }
4833                final int versionCount = versionedLib.size();
4834                for (int j = 0; j < versionCount; j++) {
4835                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
4836                    if (!libEntry.info.isStatic()) {
4837                        if (libs == null) {
4838                            libs = new ArraySet<>();
4839                        }
4840                        libs.add(libEntry.info.getName());
4841                        break;
4842                    }
4843                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
4844                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
4845                            UserHandle.getUserId(Binder.getCallingUid()),
4846                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
4847                        if (libs == null) {
4848                            libs = new ArraySet<>();
4849                        }
4850                        libs.add(libEntry.info.getName());
4851                        break;
4852                    }
4853                }
4854            }
4855
4856            if (libs != null) {
4857                String[] libsArray = new String[libs.size()];
4858                libs.toArray(libsArray);
4859                return libsArray;
4860            }
4861
4862            return null;
4863        }
4864    }
4865
4866    @Override
4867    public @NonNull String getServicesSystemSharedLibraryPackageName() {
4868        // allow instant applications
4869        synchronized (mPackages) {
4870            return mServicesSystemSharedLibraryPackageName;
4871        }
4872    }
4873
4874    @Override
4875    public @NonNull String getSharedSystemSharedLibraryPackageName() {
4876        // allow instant applications
4877        synchronized (mPackages) {
4878            return mSharedSystemSharedLibraryPackageName;
4879        }
4880    }
4881
4882    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
4883        for (int i = userList.length - 1; i >= 0; --i) {
4884            final int userId = userList[i];
4885            // don't add instant app to the list of updates
4886            if (pkgSetting.getInstantApp(userId)) {
4887                continue;
4888            }
4889            SparseArray<String> changedPackages = mChangedPackages.get(userId);
4890            if (changedPackages == null) {
4891                changedPackages = new SparseArray<>();
4892                mChangedPackages.put(userId, changedPackages);
4893            }
4894            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
4895            if (sequenceNumbers == null) {
4896                sequenceNumbers = new HashMap<>();
4897                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
4898            }
4899            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
4900            if (sequenceNumber != null) {
4901                changedPackages.remove(sequenceNumber);
4902            }
4903            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
4904            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
4905        }
4906        mChangedPackagesSequenceNumber++;
4907    }
4908
4909    @Override
4910    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
4911        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4912            return null;
4913        }
4914        synchronized (mPackages) {
4915            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
4916                return null;
4917            }
4918            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
4919            if (changedPackages == null) {
4920                return null;
4921            }
4922            final List<String> packageNames =
4923                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
4924            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
4925                final String packageName = changedPackages.get(i);
4926                if (packageName != null) {
4927                    packageNames.add(packageName);
4928                }
4929            }
4930            return packageNames.isEmpty()
4931                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
4932        }
4933    }
4934
4935    @Override
4936    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
4937        // allow instant applications
4938        ArrayList<FeatureInfo> res;
4939        synchronized (mAvailableFeatures) {
4940            res = new ArrayList<>(mAvailableFeatures.size() + 1);
4941            res.addAll(mAvailableFeatures.values());
4942        }
4943        final FeatureInfo fi = new FeatureInfo();
4944        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
4945                FeatureInfo.GL_ES_VERSION_UNDEFINED);
4946        res.add(fi);
4947
4948        return new ParceledListSlice<>(res);
4949    }
4950
4951    @Override
4952    public boolean hasSystemFeature(String name, int version) {
4953        // allow instant applications
4954        synchronized (mAvailableFeatures) {
4955            final FeatureInfo feat = mAvailableFeatures.get(name);
4956            if (feat == null) {
4957                return false;
4958            } else {
4959                return feat.version >= version;
4960            }
4961        }
4962    }
4963
4964    @Override
4965    public int checkPermission(String permName, String pkgName, int userId) {
4966        if (!sUserManager.exists(userId)) {
4967            return PackageManager.PERMISSION_DENIED;
4968        }
4969        final int callingUid = Binder.getCallingUid();
4970
4971        synchronized (mPackages) {
4972            final PackageParser.Package p = mPackages.get(pkgName);
4973            if (p != null && p.mExtras != null) {
4974                final PackageSetting ps = (PackageSetting) p.mExtras;
4975                if (filterAppAccessLPr(ps, callingUid, userId)) {
4976                    return PackageManager.PERMISSION_DENIED;
4977                }
4978                final boolean instantApp = ps.getInstantApp(userId);
4979                final PermissionsState permissionsState = ps.getPermissionsState();
4980                if (permissionsState.hasPermission(permName, userId)) {
4981                    if (instantApp) {
4982                        BasePermission bp = mSettings.mPermissions.get(permName);
4983                        if (bp != null && bp.isInstant()) {
4984                            return PackageManager.PERMISSION_GRANTED;
4985                        }
4986                    } else {
4987                        return PackageManager.PERMISSION_GRANTED;
4988                    }
4989                }
4990                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
4991                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
4992                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
4993                    return PackageManager.PERMISSION_GRANTED;
4994                }
4995            }
4996        }
4997
4998        return PackageManager.PERMISSION_DENIED;
4999    }
5000
5001    @Override
5002    public int checkUidPermission(String permName, int uid) {
5003        final int callingUid = Binder.getCallingUid();
5004        final int callingUserId = UserHandle.getUserId(callingUid);
5005        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5006        final boolean isUidInstantApp = getInstantAppPackageName(uid) != null;
5007        final int userId = UserHandle.getUserId(uid);
5008        if (!sUserManager.exists(userId)) {
5009            return PackageManager.PERMISSION_DENIED;
5010        }
5011
5012        synchronized (mPackages) {
5013            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5014            if (obj != null) {
5015                if (obj instanceof SharedUserSetting) {
5016                    if (isCallerInstantApp) {
5017                        return PackageManager.PERMISSION_DENIED;
5018                    }
5019                } else if (obj instanceof PackageSetting) {
5020                    final PackageSetting ps = (PackageSetting) obj;
5021                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5022                        return PackageManager.PERMISSION_DENIED;
5023                    }
5024                }
5025                final SettingBase settingBase = (SettingBase) obj;
5026                final PermissionsState permissionsState = settingBase.getPermissionsState();
5027                if (permissionsState.hasPermission(permName, userId)) {
5028                    if (isUidInstantApp) {
5029                        BasePermission bp = mSettings.mPermissions.get(permName);
5030                        if (bp != null && bp.isInstant()) {
5031                            return PackageManager.PERMISSION_GRANTED;
5032                        }
5033                    } else {
5034                        return PackageManager.PERMISSION_GRANTED;
5035                    }
5036                }
5037                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5038                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5039                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5040                    return PackageManager.PERMISSION_GRANTED;
5041                }
5042            } else {
5043                ArraySet<String> perms = mSystemPermissions.get(uid);
5044                if (perms != null) {
5045                    if (perms.contains(permName)) {
5046                        return PackageManager.PERMISSION_GRANTED;
5047                    }
5048                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
5049                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
5050                        return PackageManager.PERMISSION_GRANTED;
5051                    }
5052                }
5053            }
5054        }
5055
5056        return PackageManager.PERMISSION_DENIED;
5057    }
5058
5059    @Override
5060    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5061        if (UserHandle.getCallingUserId() != userId) {
5062            mContext.enforceCallingPermission(
5063                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5064                    "isPermissionRevokedByPolicy for user " + userId);
5065        }
5066
5067        if (checkPermission(permission, packageName, userId)
5068                == PackageManager.PERMISSION_GRANTED) {
5069            return false;
5070        }
5071
5072        final int callingUid = Binder.getCallingUid();
5073        if (getInstantAppPackageName(callingUid) != null) {
5074            if (!isCallerSameApp(packageName, callingUid)) {
5075                return false;
5076            }
5077        } else {
5078            if (isInstantApp(packageName, userId)) {
5079                return false;
5080            }
5081        }
5082
5083        final long identity = Binder.clearCallingIdentity();
5084        try {
5085            final int flags = getPermissionFlags(permission, packageName, userId);
5086            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5087        } finally {
5088            Binder.restoreCallingIdentity(identity);
5089        }
5090    }
5091
5092    @Override
5093    public String getPermissionControllerPackageName() {
5094        synchronized (mPackages) {
5095            return mRequiredInstallerPackage;
5096        }
5097    }
5098
5099    /**
5100     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
5101     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
5102     * @param checkShell whether to prevent shell from access if there's a debugging restriction
5103     * @param message the message to log on security exception
5104     */
5105    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
5106            boolean checkShell, String message) {
5107        if (userId < 0) {
5108            throw new IllegalArgumentException("Invalid userId " + userId);
5109        }
5110        if (checkShell) {
5111            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
5112        }
5113        if (userId == UserHandle.getUserId(callingUid)) return;
5114        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5115            if (requireFullPermission) {
5116                mContext.enforceCallingOrSelfPermission(
5117                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5118            } else {
5119                try {
5120                    mContext.enforceCallingOrSelfPermission(
5121                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5122                } catch (SecurityException se) {
5123                    mContext.enforceCallingOrSelfPermission(
5124                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
5125                }
5126            }
5127        }
5128    }
5129
5130    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
5131        if (callingUid == Process.SHELL_UID) {
5132            if (userHandle >= 0
5133                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
5134                throw new SecurityException("Shell does not have permission to access user "
5135                        + userHandle);
5136            } else if (userHandle < 0) {
5137                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
5138                        + Debug.getCallers(3));
5139            }
5140        }
5141    }
5142
5143    private BasePermission findPermissionTreeLP(String permName) {
5144        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
5145            if (permName.startsWith(bp.name) &&
5146                    permName.length() > bp.name.length() &&
5147                    permName.charAt(bp.name.length()) == '.') {
5148                return bp;
5149            }
5150        }
5151        return null;
5152    }
5153
5154    private BasePermission checkPermissionTreeLP(String permName) {
5155        if (permName != null) {
5156            BasePermission bp = findPermissionTreeLP(permName);
5157            if (bp != null) {
5158                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
5159                    return bp;
5160                }
5161                throw new SecurityException("Calling uid "
5162                        + Binder.getCallingUid()
5163                        + " is not allowed to add to permission tree "
5164                        + bp.name + " owned by uid " + bp.uid);
5165            }
5166        }
5167        throw new SecurityException("No permission tree found for " + permName);
5168    }
5169
5170    static boolean compareStrings(CharSequence s1, CharSequence s2) {
5171        if (s1 == null) {
5172            return s2 == null;
5173        }
5174        if (s2 == null) {
5175            return false;
5176        }
5177        if (s1.getClass() != s2.getClass()) {
5178            return false;
5179        }
5180        return s1.equals(s2);
5181    }
5182
5183    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
5184        if (pi1.icon != pi2.icon) return false;
5185        if (pi1.logo != pi2.logo) return false;
5186        if (pi1.protectionLevel != pi2.protectionLevel) return false;
5187        if (!compareStrings(pi1.name, pi2.name)) return false;
5188        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
5189        // We'll take care of setting this one.
5190        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
5191        // These are not currently stored in settings.
5192        //if (!compareStrings(pi1.group, pi2.group)) return false;
5193        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
5194        //if (pi1.labelRes != pi2.labelRes) return false;
5195        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
5196        return true;
5197    }
5198
5199    int permissionInfoFootprint(PermissionInfo info) {
5200        int size = info.name.length();
5201        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
5202        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
5203        return size;
5204    }
5205
5206    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
5207        int size = 0;
5208        for (BasePermission perm : mSettings.mPermissions.values()) {
5209            if (perm.uid == tree.uid) {
5210                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
5211            }
5212        }
5213        return size;
5214    }
5215
5216    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
5217        // We calculate the max size of permissions defined by this uid and throw
5218        // if that plus the size of 'info' would exceed our stated maximum.
5219        if (tree.uid != Process.SYSTEM_UID) {
5220            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
5221            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
5222                throw new SecurityException("Permission tree size cap exceeded");
5223            }
5224        }
5225    }
5226
5227    boolean addPermissionLocked(PermissionInfo info, boolean async) {
5228        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5229            throw new SecurityException("Instant apps can't add permissions");
5230        }
5231        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
5232            throw new SecurityException("Label must be specified in permission");
5233        }
5234        BasePermission tree = checkPermissionTreeLP(info.name);
5235        BasePermission bp = mSettings.mPermissions.get(info.name);
5236        boolean added = bp == null;
5237        boolean changed = true;
5238        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
5239        if (added) {
5240            enforcePermissionCapLocked(info, tree);
5241            bp = new BasePermission(info.name, tree.sourcePackage,
5242                    BasePermission.TYPE_DYNAMIC);
5243        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
5244            throw new SecurityException(
5245                    "Not allowed to modify non-dynamic permission "
5246                    + info.name);
5247        } else {
5248            if (bp.protectionLevel == fixedLevel
5249                    && bp.perm.owner.equals(tree.perm.owner)
5250                    && bp.uid == tree.uid
5251                    && comparePermissionInfos(bp.perm.info, info)) {
5252                changed = false;
5253            }
5254        }
5255        bp.protectionLevel = fixedLevel;
5256        info = new PermissionInfo(info);
5257        info.protectionLevel = fixedLevel;
5258        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
5259        bp.perm.info.packageName = tree.perm.info.packageName;
5260        bp.uid = tree.uid;
5261        if (added) {
5262            mSettings.mPermissions.put(info.name, bp);
5263        }
5264        if (changed) {
5265            if (!async) {
5266                mSettings.writeLPr();
5267            } else {
5268                scheduleWriteSettingsLocked();
5269            }
5270        }
5271        return added;
5272    }
5273
5274    @Override
5275    public boolean addPermission(PermissionInfo info) {
5276        synchronized (mPackages) {
5277            return addPermissionLocked(info, false);
5278        }
5279    }
5280
5281    @Override
5282    public boolean addPermissionAsync(PermissionInfo info) {
5283        synchronized (mPackages) {
5284            return addPermissionLocked(info, true);
5285        }
5286    }
5287
5288    @Override
5289    public void removePermission(String name) {
5290        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5291            throw new SecurityException("Instant applications don't have access to this method");
5292        }
5293        synchronized (mPackages) {
5294            checkPermissionTreeLP(name);
5295            BasePermission bp = mSettings.mPermissions.get(name);
5296            if (bp != null) {
5297                if (bp.type != BasePermission.TYPE_DYNAMIC) {
5298                    throw new SecurityException(
5299                            "Not allowed to modify non-dynamic permission "
5300                            + name);
5301                }
5302                mSettings.mPermissions.remove(name);
5303                mSettings.writeLPr();
5304            }
5305        }
5306    }
5307
5308    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(
5309            PackageParser.Package pkg, BasePermission bp) {
5310        int index = pkg.requestedPermissions.indexOf(bp.name);
5311        if (index == -1) {
5312            throw new SecurityException("Package " + pkg.packageName
5313                    + " has not requested permission " + bp.name);
5314        }
5315        if (!bp.isRuntime() && !bp.isDevelopment()) {
5316            throw new SecurityException("Permission " + bp.name
5317                    + " is not a changeable permission type");
5318        }
5319    }
5320
5321    @Override
5322    public void grantRuntimePermission(String packageName, String name, final int userId) {
5323        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5324    }
5325
5326    private void grantRuntimePermission(String packageName, String name, final int userId,
5327            boolean overridePolicy) {
5328        if (!sUserManager.exists(userId)) {
5329            Log.e(TAG, "No such user:" + userId);
5330            return;
5331        }
5332        final int callingUid = Binder.getCallingUid();
5333
5334        mContext.enforceCallingOrSelfPermission(
5335                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
5336                "grantRuntimePermission");
5337
5338        enforceCrossUserPermission(callingUid, userId,
5339                true /* requireFullPermission */, true /* checkShell */,
5340                "grantRuntimePermission");
5341
5342        final int uid;
5343        final PackageSetting ps;
5344
5345        synchronized (mPackages) {
5346            final PackageParser.Package pkg = mPackages.get(packageName);
5347            if (pkg == null) {
5348                throw new IllegalArgumentException("Unknown package: " + packageName);
5349            }
5350            final BasePermission bp = mSettings.mPermissions.get(name);
5351            if (bp == null) {
5352                throw new IllegalArgumentException("Unknown permission: " + name);
5353            }
5354            ps = (PackageSetting) pkg.mExtras;
5355            if (ps == null
5356                    || filterAppAccessLPr(ps, callingUid, userId)) {
5357                throw new IllegalArgumentException("Unknown package: " + packageName);
5358            }
5359
5360            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5361
5362            // If a permission review is required for legacy apps we represent
5363            // their permissions as always granted runtime ones since we need
5364            // to keep the review required permission flag per user while an
5365            // install permission's state is shared across all users.
5366            if (mPermissionReviewRequired
5367                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5368                    && bp.isRuntime()) {
5369                return;
5370            }
5371
5372            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
5373
5374            final PermissionsState permissionsState = ps.getPermissionsState();
5375
5376            final int flags = permissionsState.getPermissionFlags(name, userId);
5377            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5378                throw new SecurityException("Cannot grant system fixed permission "
5379                        + name + " for package " + packageName);
5380            }
5381            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5382                throw new SecurityException("Cannot grant policy fixed permission "
5383                        + name + " for package " + packageName);
5384            }
5385
5386            if (bp.isDevelopment()) {
5387                // Development permissions must be handled specially, since they are not
5388                // normal runtime permissions.  For now they apply to all users.
5389                if (permissionsState.grantInstallPermission(bp) !=
5390                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5391                    scheduleWriteSettingsLocked();
5392                }
5393                return;
5394            }
5395
5396            if (ps.getInstantApp(userId) && !bp.isInstant()) {
5397                throw new SecurityException("Cannot grant non-ephemeral permission"
5398                        + name + " for package " + packageName);
5399            }
5400
5401            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
5402                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
5403                return;
5404            }
5405
5406            final int result = permissionsState.grantRuntimePermission(bp, userId);
5407            switch (result) {
5408                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
5409                    return;
5410                }
5411
5412                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
5413                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5414                    mHandler.post(new Runnable() {
5415                        @Override
5416                        public void run() {
5417                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
5418                        }
5419                    });
5420                }
5421                break;
5422            }
5423
5424            if (bp.isRuntime()) {
5425                logPermissionGranted(mContext, name, packageName);
5426            }
5427
5428            mOnPermissionChangeListeners.onPermissionsChanged(uid);
5429
5430            // Not critical if that is lost - app has to request again.
5431            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5432        }
5433
5434        // Only need to do this if user is initialized. Otherwise it's a new user
5435        // and there are no processes running as the user yet and there's no need
5436        // to make an expensive call to remount processes for the changed permissions.
5437        if (READ_EXTERNAL_STORAGE.equals(name)
5438                || WRITE_EXTERNAL_STORAGE.equals(name)) {
5439            final long token = Binder.clearCallingIdentity();
5440            try {
5441                if (sUserManager.isInitialized(userId)) {
5442                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
5443                            StorageManagerInternal.class);
5444                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
5445                }
5446            } finally {
5447                Binder.restoreCallingIdentity(token);
5448            }
5449        }
5450    }
5451
5452    @Override
5453    public void revokeRuntimePermission(String packageName, String name, int userId) {
5454        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5455    }
5456
5457    private void revokeRuntimePermission(String packageName, String name, int userId,
5458            boolean overridePolicy) {
5459        if (!sUserManager.exists(userId)) {
5460            Log.e(TAG, "No such user:" + userId);
5461            return;
5462        }
5463
5464        mContext.enforceCallingOrSelfPermission(
5465                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5466                "revokeRuntimePermission");
5467
5468        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5469                true /* requireFullPermission */, true /* checkShell */,
5470                "revokeRuntimePermission");
5471
5472        final int appId;
5473
5474        synchronized (mPackages) {
5475            final PackageParser.Package pkg = mPackages.get(packageName);
5476            if (pkg == null) {
5477                throw new IllegalArgumentException("Unknown package: " + packageName);
5478            }
5479            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5480            if (ps == null
5481                    || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
5482                throw new IllegalArgumentException("Unknown package: " + packageName);
5483            }
5484            final BasePermission bp = mSettings.mPermissions.get(name);
5485            if (bp == null) {
5486                throw new IllegalArgumentException("Unknown permission: " + name);
5487            }
5488
5489            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5490
5491            // If a permission review is required for legacy apps we represent
5492            // their permissions as always granted runtime ones since we need
5493            // to keep the review required permission flag per user while an
5494            // install permission's state is shared across all users.
5495            if (mPermissionReviewRequired
5496                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5497                    && bp.isRuntime()) {
5498                return;
5499            }
5500
5501            final PermissionsState permissionsState = ps.getPermissionsState();
5502
5503            final int flags = permissionsState.getPermissionFlags(name, userId);
5504            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5505                throw new SecurityException("Cannot revoke system fixed permission "
5506                        + name + " for package " + packageName);
5507            }
5508            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5509                throw new SecurityException("Cannot revoke policy fixed permission "
5510                        + name + " for package " + packageName);
5511            }
5512
5513            if (bp.isDevelopment()) {
5514                // Development permissions must be handled specially, since they are not
5515                // normal runtime permissions.  For now they apply to all users.
5516                if (permissionsState.revokeInstallPermission(bp) !=
5517                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5518                    scheduleWriteSettingsLocked();
5519                }
5520                return;
5521            }
5522
5523            if (permissionsState.revokeRuntimePermission(bp, userId) ==
5524                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
5525                return;
5526            }
5527
5528            if (bp.isRuntime()) {
5529                logPermissionRevoked(mContext, name, packageName);
5530            }
5531
5532            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
5533
5534            // Critical, after this call app should never have the permission.
5535            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
5536
5537            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5538        }
5539
5540        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
5541    }
5542
5543    /**
5544     * Get the first event id for the permission.
5545     *
5546     * <p>There are four events for each permission: <ul>
5547     *     <li>Request permission: first id + 0</li>
5548     *     <li>Grant permission: first id + 1</li>
5549     *     <li>Request for permission denied: first id + 2</li>
5550     *     <li>Revoke permission: first id + 3</li>
5551     * </ul></p>
5552     *
5553     * @param name name of the permission
5554     *
5555     * @return The first event id for the permission
5556     */
5557    private static int getBaseEventId(@NonNull String name) {
5558        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
5559
5560        if (eventIdIndex == -1) {
5561            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
5562                    || Build.IS_USER) {
5563                Log.i(TAG, "Unknown permission " + name);
5564
5565                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
5566            } else {
5567                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
5568                //
5569                // Also update
5570                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
5571                // - metrics_constants.proto
5572                throw new IllegalStateException("Unknown permission " + name);
5573            }
5574        }
5575
5576        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
5577    }
5578
5579    /**
5580     * Log that a permission was revoked.
5581     *
5582     * @param context Context of the caller
5583     * @param name name of the permission
5584     * @param packageName package permission if for
5585     */
5586    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
5587            @NonNull String packageName) {
5588        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
5589    }
5590
5591    /**
5592     * Log that a permission request was granted.
5593     *
5594     * @param context Context of the caller
5595     * @param name name of the permission
5596     * @param packageName package permission if for
5597     */
5598    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
5599            @NonNull String packageName) {
5600        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
5601    }
5602
5603    @Override
5604    public void resetRuntimePermissions() {
5605        mContext.enforceCallingOrSelfPermission(
5606                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5607                "revokeRuntimePermission");
5608
5609        int callingUid = Binder.getCallingUid();
5610        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5611            mContext.enforceCallingOrSelfPermission(
5612                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5613                    "resetRuntimePermissions");
5614        }
5615
5616        synchronized (mPackages) {
5617            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
5618            for (int userId : UserManagerService.getInstance().getUserIds()) {
5619                final int packageCount = mPackages.size();
5620                for (int i = 0; i < packageCount; i++) {
5621                    PackageParser.Package pkg = mPackages.valueAt(i);
5622                    if (!(pkg.mExtras instanceof PackageSetting)) {
5623                        continue;
5624                    }
5625                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5626                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5627                }
5628            }
5629        }
5630    }
5631
5632    @Override
5633    public int getPermissionFlags(String name, String packageName, int userId) {
5634        if (!sUserManager.exists(userId)) {
5635            return 0;
5636        }
5637
5638        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
5639
5640        final int callingUid = Binder.getCallingUid();
5641        enforceCrossUserPermission(callingUid, userId,
5642                true /* requireFullPermission */, false /* checkShell */,
5643                "getPermissionFlags");
5644
5645        synchronized (mPackages) {
5646            final PackageParser.Package pkg = mPackages.get(packageName);
5647            if (pkg == null) {
5648                return 0;
5649            }
5650            final BasePermission bp = mSettings.mPermissions.get(name);
5651            if (bp == null) {
5652                return 0;
5653            }
5654            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5655            if (ps == null
5656                    || filterAppAccessLPr(ps, callingUid, userId)) {
5657                return 0;
5658            }
5659            PermissionsState permissionsState = ps.getPermissionsState();
5660            return permissionsState.getPermissionFlags(name, userId);
5661        }
5662    }
5663
5664    @Override
5665    public void updatePermissionFlags(String name, String packageName, int flagMask,
5666            int flagValues, int userId) {
5667        if (!sUserManager.exists(userId)) {
5668            return;
5669        }
5670
5671        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
5672
5673        final int callingUid = Binder.getCallingUid();
5674        enforceCrossUserPermission(callingUid, userId,
5675                true /* requireFullPermission */, true /* checkShell */,
5676                "updatePermissionFlags");
5677
5678        // Only the system can change these flags and nothing else.
5679        if (getCallingUid() != Process.SYSTEM_UID) {
5680            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5681            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5682            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5683            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5684            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
5685        }
5686
5687        synchronized (mPackages) {
5688            final PackageParser.Package pkg = mPackages.get(packageName);
5689            if (pkg == null) {
5690                throw new IllegalArgumentException("Unknown package: " + packageName);
5691            }
5692            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5693            if (ps == null
5694                    || filterAppAccessLPr(ps, callingUid, userId)) {
5695                throw new IllegalArgumentException("Unknown package: " + packageName);
5696            }
5697
5698            final BasePermission bp = mSettings.mPermissions.get(name);
5699            if (bp == null) {
5700                throw new IllegalArgumentException("Unknown permission: " + name);
5701            }
5702
5703            PermissionsState permissionsState = ps.getPermissionsState();
5704
5705            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
5706
5707            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
5708                // Install and runtime permissions are stored in different places,
5709                // so figure out what permission changed and persist the change.
5710                if (permissionsState.getInstallPermissionState(name) != null) {
5711                    scheduleWriteSettingsLocked();
5712                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
5713                        || hadState) {
5714                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5715                }
5716            }
5717        }
5718    }
5719
5720    /**
5721     * Update the permission flags for all packages and runtime permissions of a user in order
5722     * to allow device or profile owner to remove POLICY_FIXED.
5723     */
5724    @Override
5725    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5726        if (!sUserManager.exists(userId)) {
5727            return;
5728        }
5729
5730        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
5731
5732        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5733                true /* requireFullPermission */, true /* checkShell */,
5734                "updatePermissionFlagsForAllApps");
5735
5736        // Only the system can change system fixed flags.
5737        if (getCallingUid() != Process.SYSTEM_UID) {
5738            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5739            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5740        }
5741
5742        synchronized (mPackages) {
5743            boolean changed = false;
5744            final int packageCount = mPackages.size();
5745            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
5746                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
5747                final PackageSetting ps = (PackageSetting) pkg.mExtras;
5748                if (ps == null) {
5749                    continue;
5750                }
5751                PermissionsState permissionsState = ps.getPermissionsState();
5752                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
5753                        userId, flagMask, flagValues);
5754            }
5755            if (changed) {
5756                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5757            }
5758        }
5759    }
5760
5761    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
5762        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
5763                != PackageManager.PERMISSION_GRANTED
5764            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
5765                != PackageManager.PERMISSION_GRANTED) {
5766            throw new SecurityException(message + " requires "
5767                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
5768                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
5769        }
5770    }
5771
5772    @Override
5773    public boolean shouldShowRequestPermissionRationale(String permissionName,
5774            String packageName, int userId) {
5775        if (UserHandle.getCallingUserId() != userId) {
5776            mContext.enforceCallingPermission(
5777                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5778                    "canShowRequestPermissionRationale for user " + userId);
5779        }
5780
5781        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5782        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5783            return false;
5784        }
5785
5786        if (checkPermission(permissionName, packageName, userId)
5787                == PackageManager.PERMISSION_GRANTED) {
5788            return false;
5789        }
5790
5791        final int flags;
5792
5793        final long identity = Binder.clearCallingIdentity();
5794        try {
5795            flags = getPermissionFlags(permissionName,
5796                    packageName, userId);
5797        } finally {
5798            Binder.restoreCallingIdentity(identity);
5799        }
5800
5801        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5802                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5803                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5804
5805        if ((flags & fixedFlags) != 0) {
5806            return false;
5807        }
5808
5809        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5810    }
5811
5812    @Override
5813    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5814        mContext.enforceCallingOrSelfPermission(
5815                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5816                "addOnPermissionsChangeListener");
5817
5818        synchronized (mPackages) {
5819            mOnPermissionChangeListeners.addListenerLocked(listener);
5820        }
5821    }
5822
5823    @Override
5824    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5825        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5826            throw new SecurityException("Instant applications don't have access to this method");
5827        }
5828        synchronized (mPackages) {
5829            mOnPermissionChangeListeners.removeListenerLocked(listener);
5830        }
5831    }
5832
5833    @Override
5834    public boolean isProtectedBroadcast(String actionName) {
5835        // allow instant applications
5836        synchronized (mProtectedBroadcasts) {
5837            if (mProtectedBroadcasts.contains(actionName)) {
5838                return true;
5839            } else if (actionName != null) {
5840                // TODO: remove these terrible hacks
5841                if (actionName.startsWith("android.net.netmon.lingerExpired")
5842                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5843                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5844                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5845                    return true;
5846                }
5847            }
5848        }
5849        return false;
5850    }
5851
5852    @Override
5853    public int checkSignatures(String pkg1, String pkg2) {
5854        synchronized (mPackages) {
5855            final PackageParser.Package p1 = mPackages.get(pkg1);
5856            final PackageParser.Package p2 = mPackages.get(pkg2);
5857            if (p1 == null || p1.mExtras == null
5858                    || p2 == null || p2.mExtras == null) {
5859                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5860            }
5861            final int callingUid = Binder.getCallingUid();
5862            final int callingUserId = UserHandle.getUserId(callingUid);
5863            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
5864            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
5865            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
5866                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
5867                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5868            }
5869            return compareSignatures(p1.mSignatures, p2.mSignatures);
5870        }
5871    }
5872
5873    @Override
5874    public int checkUidSignatures(int uid1, int uid2) {
5875        final int callingUid = Binder.getCallingUid();
5876        final int callingUserId = UserHandle.getUserId(callingUid);
5877        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5878        // Map to base uids.
5879        uid1 = UserHandle.getAppId(uid1);
5880        uid2 = UserHandle.getAppId(uid2);
5881        // reader
5882        synchronized (mPackages) {
5883            Signature[] s1;
5884            Signature[] s2;
5885            Object obj = mSettings.getUserIdLPr(uid1);
5886            if (obj != null) {
5887                if (obj instanceof SharedUserSetting) {
5888                    if (isCallerInstantApp) {
5889                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5890                    }
5891                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
5892                } else if (obj instanceof PackageSetting) {
5893                    final PackageSetting ps = (PackageSetting) obj;
5894                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5895                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5896                    }
5897                    s1 = ps.signatures.mSignatures;
5898                } else {
5899                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5900                }
5901            } else {
5902                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5903            }
5904            obj = mSettings.getUserIdLPr(uid2);
5905            if (obj != null) {
5906                if (obj instanceof SharedUserSetting) {
5907                    if (isCallerInstantApp) {
5908                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5909                    }
5910                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
5911                } else if (obj instanceof PackageSetting) {
5912                    final PackageSetting ps = (PackageSetting) obj;
5913                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5914                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5915                    }
5916                    s2 = ps.signatures.mSignatures;
5917                } else {
5918                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5919                }
5920            } else {
5921                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5922            }
5923            return compareSignatures(s1, s2);
5924        }
5925    }
5926
5927    /**
5928     * This method should typically only be used when granting or revoking
5929     * permissions, since the app may immediately restart after this call.
5930     * <p>
5931     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5932     * guard your work against the app being relaunched.
5933     */
5934    private void killUid(int appId, int userId, String reason) {
5935        final long identity = Binder.clearCallingIdentity();
5936        try {
5937            IActivityManager am = ActivityManager.getService();
5938            if (am != null) {
5939                try {
5940                    am.killUid(appId, userId, reason);
5941                } catch (RemoteException e) {
5942                    /* ignore - same process */
5943                }
5944            }
5945        } finally {
5946            Binder.restoreCallingIdentity(identity);
5947        }
5948    }
5949
5950    /**
5951     * Compares two sets of signatures. Returns:
5952     * <br />
5953     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
5954     * <br />
5955     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
5956     * <br />
5957     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
5958     * <br />
5959     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
5960     * <br />
5961     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
5962     */
5963    static int compareSignatures(Signature[] s1, Signature[] s2) {
5964        if (s1 == null) {
5965            return s2 == null
5966                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
5967                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
5968        }
5969
5970        if (s2 == null) {
5971            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
5972        }
5973
5974        if (s1.length != s2.length) {
5975            return PackageManager.SIGNATURE_NO_MATCH;
5976        }
5977
5978        // Since both signature sets are of size 1, we can compare without HashSets.
5979        if (s1.length == 1) {
5980            return s1[0].equals(s2[0]) ?
5981                    PackageManager.SIGNATURE_MATCH :
5982                    PackageManager.SIGNATURE_NO_MATCH;
5983        }
5984
5985        ArraySet<Signature> set1 = new ArraySet<Signature>();
5986        for (Signature sig : s1) {
5987            set1.add(sig);
5988        }
5989        ArraySet<Signature> set2 = new ArraySet<Signature>();
5990        for (Signature sig : s2) {
5991            set2.add(sig);
5992        }
5993        // Make sure s2 contains all signatures in s1.
5994        if (set1.equals(set2)) {
5995            return PackageManager.SIGNATURE_MATCH;
5996        }
5997        return PackageManager.SIGNATURE_NO_MATCH;
5998    }
5999
6000    /**
6001     * If the database version for this type of package (internal storage or
6002     * external storage) is less than the version where package signatures
6003     * were updated, return true.
6004     */
6005    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6006        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6007        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
6008    }
6009
6010    /**
6011     * Used for backward compatibility to make sure any packages with
6012     * certificate chains get upgraded to the new style. {@code existingSigs}
6013     * will be in the old format (since they were stored on disk from before the
6014     * system upgrade) and {@code scannedSigs} will be in the newer format.
6015     */
6016    private int compareSignaturesCompat(PackageSignatures existingSigs,
6017            PackageParser.Package scannedPkg) {
6018        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
6019            return PackageManager.SIGNATURE_NO_MATCH;
6020        }
6021
6022        ArraySet<Signature> existingSet = new ArraySet<Signature>();
6023        for (Signature sig : existingSigs.mSignatures) {
6024            existingSet.add(sig);
6025        }
6026        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
6027        for (Signature sig : scannedPkg.mSignatures) {
6028            try {
6029                Signature[] chainSignatures = sig.getChainSignatures();
6030                for (Signature chainSig : chainSignatures) {
6031                    scannedCompatSet.add(chainSig);
6032                }
6033            } catch (CertificateEncodingException e) {
6034                scannedCompatSet.add(sig);
6035            }
6036        }
6037        /*
6038         * Make sure the expanded scanned set contains all signatures in the
6039         * existing one.
6040         */
6041        if (scannedCompatSet.equals(existingSet)) {
6042            // Migrate the old signatures to the new scheme.
6043            existingSigs.assignSignatures(scannedPkg.mSignatures);
6044            // The new KeySets will be re-added later in the scanning process.
6045            synchronized (mPackages) {
6046                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
6047            }
6048            return PackageManager.SIGNATURE_MATCH;
6049        }
6050        return PackageManager.SIGNATURE_NO_MATCH;
6051    }
6052
6053    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6054        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6055        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
6056    }
6057
6058    private int compareSignaturesRecover(PackageSignatures existingSigs,
6059            PackageParser.Package scannedPkg) {
6060        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
6061            return PackageManager.SIGNATURE_NO_MATCH;
6062        }
6063
6064        String msg = null;
6065        try {
6066            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
6067                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
6068                        + scannedPkg.packageName);
6069                return PackageManager.SIGNATURE_MATCH;
6070            }
6071        } catch (CertificateException e) {
6072            msg = e.getMessage();
6073        }
6074
6075        logCriticalInfo(Log.INFO,
6076                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
6077        return PackageManager.SIGNATURE_NO_MATCH;
6078    }
6079
6080    @Override
6081    public List<String> getAllPackages() {
6082        final int callingUid = Binder.getCallingUid();
6083        final int callingUserId = UserHandle.getUserId(callingUid);
6084        synchronized (mPackages) {
6085            if (canViewInstantApps(callingUid, callingUserId)) {
6086                return new ArrayList<String>(mPackages.keySet());
6087            }
6088            final String instantAppPkgName = getInstantAppPackageName(callingUid);
6089            final List<String> result = new ArrayList<>();
6090            if (instantAppPkgName != null) {
6091                // caller is an instant application; filter unexposed applications
6092                for (PackageParser.Package pkg : mPackages.values()) {
6093                    if (!pkg.visibleToInstantApps) {
6094                        continue;
6095                    }
6096                    result.add(pkg.packageName);
6097                }
6098            } else {
6099                // caller is a normal application; filter instant applications
6100                for (PackageParser.Package pkg : mPackages.values()) {
6101                    final PackageSetting ps =
6102                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
6103                    if (ps != null
6104                            && ps.getInstantApp(callingUserId)
6105                            && !mInstantAppRegistry.isInstantAccessGranted(
6106                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
6107                        continue;
6108                    }
6109                    result.add(pkg.packageName);
6110                }
6111            }
6112            return result;
6113        }
6114    }
6115
6116    @Override
6117    public String[] getPackagesForUid(int uid) {
6118        final int callingUid = Binder.getCallingUid();
6119        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
6120        final int userId = UserHandle.getUserId(uid);
6121        uid = UserHandle.getAppId(uid);
6122        // reader
6123        synchronized (mPackages) {
6124            Object obj = mSettings.getUserIdLPr(uid);
6125            if (obj instanceof SharedUserSetting) {
6126                if (isCallerInstantApp) {
6127                    return null;
6128                }
6129                final SharedUserSetting sus = (SharedUserSetting) obj;
6130                final int N = sus.packages.size();
6131                String[] res = new String[N];
6132                final Iterator<PackageSetting> it = sus.packages.iterator();
6133                int i = 0;
6134                while (it.hasNext()) {
6135                    PackageSetting ps = it.next();
6136                    if (ps.getInstalled(userId)) {
6137                        res[i++] = ps.name;
6138                    } else {
6139                        res = ArrayUtils.removeElement(String.class, res, res[i]);
6140                    }
6141                }
6142                return res;
6143            } else if (obj instanceof PackageSetting) {
6144                final PackageSetting ps = (PackageSetting) obj;
6145                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
6146                    return new String[]{ps.name};
6147                }
6148            }
6149        }
6150        return null;
6151    }
6152
6153    @Override
6154    public String getNameForUid(int uid) {
6155        final int callingUid = Binder.getCallingUid();
6156        if (getInstantAppPackageName(callingUid) != null) {
6157            return null;
6158        }
6159        synchronized (mPackages) {
6160            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6161            if (obj instanceof SharedUserSetting) {
6162                final SharedUserSetting sus = (SharedUserSetting) obj;
6163                return sus.name + ":" + sus.userId;
6164            } else if (obj instanceof PackageSetting) {
6165                final PackageSetting ps = (PackageSetting) obj;
6166                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6167                    return null;
6168                }
6169                return ps.name;
6170            }
6171        }
6172        return null;
6173    }
6174
6175    @Override
6176    public int getUidForSharedUser(String sharedUserName) {
6177        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6178            return -1;
6179        }
6180        if (sharedUserName == null) {
6181            return -1;
6182        }
6183        // reader
6184        synchronized (mPackages) {
6185            SharedUserSetting suid;
6186            try {
6187                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
6188                if (suid != null) {
6189                    return suid.userId;
6190                }
6191            } catch (PackageManagerException ignore) {
6192                // can't happen, but, still need to catch it
6193            }
6194            return -1;
6195        }
6196    }
6197
6198    @Override
6199    public int getFlagsForUid(int uid) {
6200        final int callingUid = Binder.getCallingUid();
6201        if (getInstantAppPackageName(callingUid) != null) {
6202            return 0;
6203        }
6204        synchronized (mPackages) {
6205            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6206            if (obj instanceof SharedUserSetting) {
6207                final SharedUserSetting sus = (SharedUserSetting) obj;
6208                return sus.pkgFlags;
6209            } else if (obj instanceof PackageSetting) {
6210                final PackageSetting ps = (PackageSetting) obj;
6211                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6212                    return 0;
6213                }
6214                return ps.pkgFlags;
6215            }
6216        }
6217        return 0;
6218    }
6219
6220    @Override
6221    public int getPrivateFlagsForUid(int uid) {
6222        final int callingUid = Binder.getCallingUid();
6223        if (getInstantAppPackageName(callingUid) != null) {
6224            return 0;
6225        }
6226        synchronized (mPackages) {
6227            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6228            if (obj instanceof SharedUserSetting) {
6229                final SharedUserSetting sus = (SharedUserSetting) obj;
6230                return sus.pkgPrivateFlags;
6231            } else if (obj instanceof PackageSetting) {
6232                final PackageSetting ps = (PackageSetting) obj;
6233                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6234                    return 0;
6235                }
6236                return ps.pkgPrivateFlags;
6237            }
6238        }
6239        return 0;
6240    }
6241
6242    @Override
6243    public boolean isUidPrivileged(int uid) {
6244        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6245            return false;
6246        }
6247        uid = UserHandle.getAppId(uid);
6248        // reader
6249        synchronized (mPackages) {
6250            Object obj = mSettings.getUserIdLPr(uid);
6251            if (obj instanceof SharedUserSetting) {
6252                final SharedUserSetting sus = (SharedUserSetting) obj;
6253                final Iterator<PackageSetting> it = sus.packages.iterator();
6254                while (it.hasNext()) {
6255                    if (it.next().isPrivileged()) {
6256                        return true;
6257                    }
6258                }
6259            } else if (obj instanceof PackageSetting) {
6260                final PackageSetting ps = (PackageSetting) obj;
6261                return ps.isPrivileged();
6262            }
6263        }
6264        return false;
6265    }
6266
6267    @Override
6268    public String[] getAppOpPermissionPackages(String permissionName) {
6269        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6270            return null;
6271        }
6272        synchronized (mPackages) {
6273            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
6274            if (pkgs == null) {
6275                return null;
6276            }
6277            return pkgs.toArray(new String[pkgs.size()]);
6278        }
6279    }
6280
6281    @Override
6282    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
6283            int flags, int userId) {
6284        return resolveIntentInternal(
6285                intent, resolvedType, flags, userId, false /*includeInstantApps*/);
6286    }
6287
6288    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
6289            int flags, int userId, boolean resolveForStart) {
6290        try {
6291            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
6292
6293            if (!sUserManager.exists(userId)) return null;
6294            final int callingUid = Binder.getCallingUid();
6295            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
6296            enforceCrossUserPermission(callingUid, userId,
6297                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
6298
6299            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6300            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
6301                    flags, callingUid, userId, resolveForStart);
6302            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6303
6304            final ResolveInfo bestChoice =
6305                    chooseBestActivity(intent, resolvedType, flags, query, userId);
6306            return bestChoice;
6307        } finally {
6308            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6309        }
6310    }
6311
6312    @Override
6313    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
6314        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
6315            throw new SecurityException(
6316                    "findPersistentPreferredActivity can only be run by the system");
6317        }
6318        if (!sUserManager.exists(userId)) {
6319            return null;
6320        }
6321        final int callingUid = Binder.getCallingUid();
6322        intent = updateIntentForResolve(intent);
6323        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
6324        final int flags = updateFlagsForResolve(
6325                0, userId, intent, callingUid, false /*includeInstantApps*/);
6326        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6327                userId);
6328        synchronized (mPackages) {
6329            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
6330                    userId);
6331        }
6332    }
6333
6334    @Override
6335    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
6336            IntentFilter filter, int match, ComponentName activity) {
6337        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6338            return;
6339        }
6340        final int userId = UserHandle.getCallingUserId();
6341        if (DEBUG_PREFERRED) {
6342            Log.v(TAG, "setLastChosenActivity intent=" + intent
6343                + " resolvedType=" + resolvedType
6344                + " flags=" + flags
6345                + " filter=" + filter
6346                + " match=" + match
6347                + " activity=" + activity);
6348            filter.dump(new PrintStreamPrinter(System.out), "    ");
6349        }
6350        intent.setComponent(null);
6351        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6352                userId);
6353        // Find any earlier preferred or last chosen entries and nuke them
6354        findPreferredActivity(intent, resolvedType,
6355                flags, query, 0, false, true, false, userId);
6356        // Add the new activity as the last chosen for this filter
6357        addPreferredActivityInternal(filter, match, null, activity, false, userId,
6358                "Setting last chosen");
6359    }
6360
6361    @Override
6362    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
6363        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6364            return null;
6365        }
6366        final int userId = UserHandle.getCallingUserId();
6367        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
6368        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6369                userId);
6370        return findPreferredActivity(intent, resolvedType, flags, query, 0,
6371                false, false, false, userId);
6372    }
6373
6374    /**
6375     * Returns whether or not instant apps have been disabled remotely.
6376     */
6377    private boolean isEphemeralDisabled() {
6378        return mEphemeralAppsDisabled;
6379    }
6380
6381    private boolean isInstantAppAllowed(
6382            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
6383            boolean skipPackageCheck) {
6384        if (mInstantAppResolverConnection == null) {
6385            return false;
6386        }
6387        if (mInstantAppInstallerActivity == null) {
6388            return false;
6389        }
6390        if (intent.getComponent() != null) {
6391            return false;
6392        }
6393        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
6394            return false;
6395        }
6396        if (!skipPackageCheck && intent.getPackage() != null) {
6397            return false;
6398        }
6399        final boolean isWebUri = hasWebURI(intent);
6400        if (!isWebUri || intent.getData().getHost() == null) {
6401            return false;
6402        }
6403        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
6404        // Or if there's already an ephemeral app installed that handles the action
6405        synchronized (mPackages) {
6406            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
6407            for (int n = 0; n < count; n++) {
6408                final ResolveInfo info = resolvedActivities.get(n);
6409                final String packageName = info.activityInfo.packageName;
6410                final PackageSetting ps = mSettings.mPackages.get(packageName);
6411                if (ps != null) {
6412                    // only check domain verification status if the app is not a browser
6413                    if (!info.handleAllWebDataURI) {
6414                        // Try to get the status from User settings first
6415                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6416                        final int status = (int) (packedStatus >> 32);
6417                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
6418                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6419                            if (DEBUG_EPHEMERAL) {
6420                                Slog.v(TAG, "DENY instant app;"
6421                                    + " pkg: " + packageName + ", status: " + status);
6422                            }
6423                            return false;
6424                        }
6425                    }
6426                    if (ps.getInstantApp(userId)) {
6427                        if (DEBUG_EPHEMERAL) {
6428                            Slog.v(TAG, "DENY instant app installed;"
6429                                    + " pkg: " + packageName);
6430                        }
6431                        return false;
6432                    }
6433                }
6434            }
6435        }
6436        // We've exhausted all ways to deny ephemeral application; let the system look for them.
6437        return true;
6438    }
6439
6440    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
6441            Intent origIntent, String resolvedType, String callingPackage,
6442            Bundle verificationBundle, int userId) {
6443        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
6444                new InstantAppRequest(responseObj, origIntent, resolvedType,
6445                        callingPackage, userId, verificationBundle));
6446        mHandler.sendMessage(msg);
6447    }
6448
6449    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
6450            int flags, List<ResolveInfo> query, int userId) {
6451        if (query != null) {
6452            final int N = query.size();
6453            if (N == 1) {
6454                return query.get(0);
6455            } else if (N > 1) {
6456                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
6457                // If there is more than one activity with the same priority,
6458                // then let the user decide between them.
6459                ResolveInfo r0 = query.get(0);
6460                ResolveInfo r1 = query.get(1);
6461                if (DEBUG_INTENT_MATCHING || debug) {
6462                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
6463                            + r1.activityInfo.name + "=" + r1.priority);
6464                }
6465                // If the first activity has a higher priority, or a different
6466                // default, then it is always desirable to pick it.
6467                if (r0.priority != r1.priority
6468                        || r0.preferredOrder != r1.preferredOrder
6469                        || r0.isDefault != r1.isDefault) {
6470                    return query.get(0);
6471                }
6472                // If we have saved a preference for a preferred activity for
6473                // this Intent, use that.
6474                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
6475                        flags, query, r0.priority, true, false, debug, userId);
6476                if (ri != null) {
6477                    return ri;
6478                }
6479                // If we have an ephemeral app, use it
6480                for (int i = 0; i < N; i++) {
6481                    ri = query.get(i);
6482                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
6483                        final String packageName = ri.activityInfo.packageName;
6484                        final PackageSetting ps = mSettings.mPackages.get(packageName);
6485                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6486                        final int status = (int)(packedStatus >> 32);
6487                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6488                            return ri;
6489                        }
6490                    }
6491                }
6492                ri = new ResolveInfo(mResolveInfo);
6493                ri.activityInfo = new ActivityInfo(ri.activityInfo);
6494                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6495                // If all of the options come from the same package, show the application's
6496                // label and icon instead of the generic resolver's.
6497                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6498                // and then throw away the ResolveInfo itself, meaning that the caller loses
6499                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6500                // a fallback for this case; we only set the target package's resources on
6501                // the ResolveInfo, not the ActivityInfo.
6502                final String intentPackage = intent.getPackage();
6503                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6504                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6505                    ri.resolvePackageName = intentPackage;
6506                    if (userNeedsBadging(userId)) {
6507                        ri.noResourceId = true;
6508                    } else {
6509                        ri.icon = appi.icon;
6510                    }
6511                    ri.iconResourceId = appi.icon;
6512                    ri.labelRes = appi.labelRes;
6513                }
6514                ri.activityInfo.applicationInfo = new ApplicationInfo(
6515                        ri.activityInfo.applicationInfo);
6516                if (userId != 0) {
6517                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6518                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6519                }
6520                // Make sure that the resolver is displayable in car mode
6521                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6522                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6523                return ri;
6524            }
6525        }
6526        return null;
6527    }
6528
6529    /**
6530     * Return true if the given list is not empty and all of its contents have
6531     * an activityInfo with the given package name.
6532     */
6533    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6534        if (ArrayUtils.isEmpty(list)) {
6535            return false;
6536        }
6537        for (int i = 0, N = list.size(); i < N; i++) {
6538            final ResolveInfo ri = list.get(i);
6539            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6540            if (ai == null || !packageName.equals(ai.packageName)) {
6541                return false;
6542            }
6543        }
6544        return true;
6545    }
6546
6547    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6548            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6549        final int N = query.size();
6550        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6551                .get(userId);
6552        // Get the list of persistent preferred activities that handle the intent
6553        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6554        List<PersistentPreferredActivity> pprefs = ppir != null
6555                ? ppir.queryIntent(intent, resolvedType,
6556                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6557                        userId)
6558                : null;
6559        if (pprefs != null && pprefs.size() > 0) {
6560            final int M = pprefs.size();
6561            for (int i=0; i<M; i++) {
6562                final PersistentPreferredActivity ppa = pprefs.get(i);
6563                if (DEBUG_PREFERRED || debug) {
6564                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6565                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6566                            + "\n  component=" + ppa.mComponent);
6567                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6568                }
6569                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6570                        flags | MATCH_DISABLED_COMPONENTS, userId);
6571                if (DEBUG_PREFERRED || debug) {
6572                    Slog.v(TAG, "Found persistent preferred activity:");
6573                    if (ai != null) {
6574                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6575                    } else {
6576                        Slog.v(TAG, "  null");
6577                    }
6578                }
6579                if (ai == null) {
6580                    // This previously registered persistent preferred activity
6581                    // component is no longer known. Ignore it and do NOT remove it.
6582                    continue;
6583                }
6584                for (int j=0; j<N; j++) {
6585                    final ResolveInfo ri = query.get(j);
6586                    if (!ri.activityInfo.applicationInfo.packageName
6587                            .equals(ai.applicationInfo.packageName)) {
6588                        continue;
6589                    }
6590                    if (!ri.activityInfo.name.equals(ai.name)) {
6591                        continue;
6592                    }
6593                    //  Found a persistent preference that can handle the intent.
6594                    if (DEBUG_PREFERRED || debug) {
6595                        Slog.v(TAG, "Returning persistent preferred activity: " +
6596                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6597                    }
6598                    return ri;
6599                }
6600            }
6601        }
6602        return null;
6603    }
6604
6605    // TODO: handle preferred activities missing while user has amnesia
6606    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6607            List<ResolveInfo> query, int priority, boolean always,
6608            boolean removeMatches, boolean debug, int userId) {
6609        if (!sUserManager.exists(userId)) return null;
6610        final int callingUid = Binder.getCallingUid();
6611        flags = updateFlagsForResolve(
6612                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6613        intent = updateIntentForResolve(intent);
6614        // writer
6615        synchronized (mPackages) {
6616            // Try to find a matching persistent preferred activity.
6617            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6618                    debug, userId);
6619
6620            // If a persistent preferred activity matched, use it.
6621            if (pri != null) {
6622                return pri;
6623            }
6624
6625            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6626            // Get the list of preferred activities that handle the intent
6627            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6628            List<PreferredActivity> prefs = pir != null
6629                    ? pir.queryIntent(intent, resolvedType,
6630                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6631                            userId)
6632                    : null;
6633            if (prefs != null && prefs.size() > 0) {
6634                boolean changed = false;
6635                try {
6636                    // First figure out how good the original match set is.
6637                    // We will only allow preferred activities that came
6638                    // from the same match quality.
6639                    int match = 0;
6640
6641                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6642
6643                    final int N = query.size();
6644                    for (int j=0; j<N; j++) {
6645                        final ResolveInfo ri = query.get(j);
6646                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6647                                + ": 0x" + Integer.toHexString(match));
6648                        if (ri.match > match) {
6649                            match = ri.match;
6650                        }
6651                    }
6652
6653                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6654                            + Integer.toHexString(match));
6655
6656                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6657                    final int M = prefs.size();
6658                    for (int i=0; i<M; i++) {
6659                        final PreferredActivity pa = prefs.get(i);
6660                        if (DEBUG_PREFERRED || debug) {
6661                            Slog.v(TAG, "Checking PreferredActivity ds="
6662                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6663                                    + "\n  component=" + pa.mPref.mComponent);
6664                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6665                        }
6666                        if (pa.mPref.mMatch != match) {
6667                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6668                                    + Integer.toHexString(pa.mPref.mMatch));
6669                            continue;
6670                        }
6671                        // If it's not an "always" type preferred activity and that's what we're
6672                        // looking for, skip it.
6673                        if (always && !pa.mPref.mAlways) {
6674                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6675                            continue;
6676                        }
6677                        final ActivityInfo ai = getActivityInfo(
6678                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6679                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6680                                userId);
6681                        if (DEBUG_PREFERRED || debug) {
6682                            Slog.v(TAG, "Found preferred activity:");
6683                            if (ai != null) {
6684                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6685                            } else {
6686                                Slog.v(TAG, "  null");
6687                            }
6688                        }
6689                        if (ai == null) {
6690                            // This previously registered preferred activity
6691                            // component is no longer known.  Most likely an update
6692                            // to the app was installed and in the new version this
6693                            // component no longer exists.  Clean it up by removing
6694                            // it from the preferred activities list, and skip it.
6695                            Slog.w(TAG, "Removing dangling preferred activity: "
6696                                    + pa.mPref.mComponent);
6697                            pir.removeFilter(pa);
6698                            changed = true;
6699                            continue;
6700                        }
6701                        for (int j=0; j<N; j++) {
6702                            final ResolveInfo ri = query.get(j);
6703                            if (!ri.activityInfo.applicationInfo.packageName
6704                                    .equals(ai.applicationInfo.packageName)) {
6705                                continue;
6706                            }
6707                            if (!ri.activityInfo.name.equals(ai.name)) {
6708                                continue;
6709                            }
6710
6711                            if (removeMatches) {
6712                                pir.removeFilter(pa);
6713                                changed = true;
6714                                if (DEBUG_PREFERRED) {
6715                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6716                                }
6717                                break;
6718                            }
6719
6720                            // Okay we found a previously set preferred or last chosen app.
6721                            // If the result set is different from when this
6722                            // was created, we need to clear it and re-ask the
6723                            // user their preference, if we're looking for an "always" type entry.
6724                            if (always && !pa.mPref.sameSet(query)) {
6725                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
6726                                        + intent + " type " + resolvedType);
6727                                if (DEBUG_PREFERRED) {
6728                                    Slog.v(TAG, "Removing preferred activity since set changed "
6729                                            + pa.mPref.mComponent);
6730                                }
6731                                pir.removeFilter(pa);
6732                                // Re-add the filter as a "last chosen" entry (!always)
6733                                PreferredActivity lastChosen = new PreferredActivity(
6734                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6735                                pir.addFilter(lastChosen);
6736                                changed = true;
6737                                return null;
6738                            }
6739
6740                            // Yay! Either the set matched or we're looking for the last chosen
6741                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6742                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6743                            return ri;
6744                        }
6745                    }
6746                } finally {
6747                    if (changed) {
6748                        if (DEBUG_PREFERRED) {
6749                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6750                        }
6751                        scheduleWritePackageRestrictionsLocked(userId);
6752                    }
6753                }
6754            }
6755        }
6756        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6757        return null;
6758    }
6759
6760    /*
6761     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6762     */
6763    @Override
6764    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6765            int targetUserId) {
6766        mContext.enforceCallingOrSelfPermission(
6767                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6768        List<CrossProfileIntentFilter> matches =
6769                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6770        if (matches != null) {
6771            int size = matches.size();
6772            for (int i = 0; i < size; i++) {
6773                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6774            }
6775        }
6776        if (hasWebURI(intent)) {
6777            // cross-profile app linking works only towards the parent.
6778            final int callingUid = Binder.getCallingUid();
6779            final UserInfo parent = getProfileParent(sourceUserId);
6780            synchronized(mPackages) {
6781                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
6782                        false /*includeInstantApps*/);
6783                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6784                        intent, resolvedType, flags, sourceUserId, parent.id);
6785                return xpDomainInfo != null;
6786            }
6787        }
6788        return false;
6789    }
6790
6791    private UserInfo getProfileParent(int userId) {
6792        final long identity = Binder.clearCallingIdentity();
6793        try {
6794            return sUserManager.getProfileParent(userId);
6795        } finally {
6796            Binder.restoreCallingIdentity(identity);
6797        }
6798    }
6799
6800    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6801            String resolvedType, int userId) {
6802        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6803        if (resolver != null) {
6804            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6805        }
6806        return null;
6807    }
6808
6809    @Override
6810    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6811            String resolvedType, int flags, int userId) {
6812        try {
6813            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6814
6815            return new ParceledListSlice<>(
6816                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6817        } finally {
6818            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6819        }
6820    }
6821
6822    /**
6823     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6824     * instant, returns {@code null}.
6825     */
6826    private String getInstantAppPackageName(int callingUid) {
6827        synchronized (mPackages) {
6828            // If the caller is an isolated app use the owner's uid for the lookup.
6829            if (Process.isIsolated(callingUid)) {
6830                callingUid = mIsolatedOwners.get(callingUid);
6831            }
6832            final int appId = UserHandle.getAppId(callingUid);
6833            final Object obj = mSettings.getUserIdLPr(appId);
6834            if (obj instanceof PackageSetting) {
6835                final PackageSetting ps = (PackageSetting) obj;
6836                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6837                return isInstantApp ? ps.pkg.packageName : null;
6838            }
6839        }
6840        return null;
6841    }
6842
6843    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6844            String resolvedType, int flags, int userId) {
6845        return queryIntentActivitiesInternal(
6846                intent, resolvedType, flags, Binder.getCallingUid(), userId, false);
6847    }
6848
6849    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6850            String resolvedType, int flags, int filterCallingUid, int userId,
6851            boolean resolveForStart) {
6852        if (!sUserManager.exists(userId)) return Collections.emptyList();
6853        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
6854        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6855                false /* requireFullPermission */, false /* checkShell */,
6856                "query intent activities");
6857        final String pkgName = intent.getPackage();
6858        ComponentName comp = intent.getComponent();
6859        if (comp == null) {
6860            if (intent.getSelector() != null) {
6861                intent = intent.getSelector();
6862                comp = intent.getComponent();
6863            }
6864        }
6865
6866        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
6867                comp != null || pkgName != null /*onlyExposedExplicitly*/);
6868        if (comp != null) {
6869            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6870            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6871            if (ai != null) {
6872                // When specifying an explicit component, we prevent the activity from being
6873                // used when either 1) the calling package is normal and the activity is within
6874                // an ephemeral application or 2) the calling package is ephemeral and the
6875                // activity is not visible to ephemeral applications.
6876                final boolean matchInstantApp =
6877                        (flags & PackageManager.MATCH_INSTANT) != 0;
6878                final boolean matchVisibleToInstantAppOnly =
6879                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6880                final boolean matchExplicitlyVisibleOnly =
6881                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
6882                final boolean isCallerInstantApp =
6883                        instantAppPkgName != null;
6884                final boolean isTargetSameInstantApp =
6885                        comp.getPackageName().equals(instantAppPkgName);
6886                final boolean isTargetInstantApp =
6887                        (ai.applicationInfo.privateFlags
6888                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6889                final boolean isTargetVisibleToInstantApp =
6890                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
6891                final boolean isTargetExplicitlyVisibleToInstantApp =
6892                        isTargetVisibleToInstantApp
6893                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
6894                final boolean isTargetHiddenFromInstantApp =
6895                        !isTargetVisibleToInstantApp
6896                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
6897                final boolean blockResolution =
6898                        !isTargetSameInstantApp
6899                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6900                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6901                                        && isTargetHiddenFromInstantApp));
6902                if (!blockResolution) {
6903                    final ResolveInfo ri = new ResolveInfo();
6904                    ri.activityInfo = ai;
6905                    list.add(ri);
6906                }
6907            }
6908            return applyPostResolutionFilter(list, instantAppPkgName);
6909        }
6910
6911        // reader
6912        boolean sortResult = false;
6913        boolean addEphemeral = false;
6914        List<ResolveInfo> result;
6915        final boolean ephemeralDisabled = isEphemeralDisabled();
6916        synchronized (mPackages) {
6917            if (pkgName == null) {
6918                List<CrossProfileIntentFilter> matchingFilters =
6919                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6920                // Check for results that need to skip the current profile.
6921                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6922                        resolvedType, flags, userId);
6923                if (xpResolveInfo != null) {
6924                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6925                    xpResult.add(xpResolveInfo);
6926                    return applyPostResolutionFilter(
6927                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName);
6928                }
6929
6930                // Check for results in the current profile.
6931                result = filterIfNotSystemUser(mActivities.queryIntent(
6932                        intent, resolvedType, flags, userId), userId);
6933                addEphemeral = !ephemeralDisabled
6934                        && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/);
6935                // Check for cross profile results.
6936                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6937                xpResolveInfo = queryCrossProfileIntents(
6938                        matchingFilters, intent, resolvedType, flags, userId,
6939                        hasNonNegativePriorityResult);
6940                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6941                    boolean isVisibleToUser = filterIfNotSystemUser(
6942                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6943                    if (isVisibleToUser) {
6944                        result.add(xpResolveInfo);
6945                        sortResult = true;
6946                    }
6947                }
6948                if (hasWebURI(intent)) {
6949                    CrossProfileDomainInfo xpDomainInfo = null;
6950                    final UserInfo parent = getProfileParent(userId);
6951                    if (parent != null) {
6952                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6953                                flags, userId, parent.id);
6954                    }
6955                    if (xpDomainInfo != null) {
6956                        if (xpResolveInfo != null) {
6957                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6958                            // in the result.
6959                            result.remove(xpResolveInfo);
6960                        }
6961                        if (result.size() == 0 && !addEphemeral) {
6962                            // No result in current profile, but found candidate in parent user.
6963                            // And we are not going to add emphemeral app, so we can return the
6964                            // result straight away.
6965                            result.add(xpDomainInfo.resolveInfo);
6966                            return applyPostResolutionFilter(result, instantAppPkgName);
6967                        }
6968                    } else if (result.size() <= 1 && !addEphemeral) {
6969                        // No result in parent user and <= 1 result in current profile, and we
6970                        // are not going to add emphemeral app, so we can return the result without
6971                        // further processing.
6972                        return applyPostResolutionFilter(result, instantAppPkgName);
6973                    }
6974                    // We have more than one candidate (combining results from current and parent
6975                    // profile), so we need filtering and sorting.
6976                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6977                            intent, flags, result, xpDomainInfo, userId);
6978                    sortResult = true;
6979                }
6980            } else {
6981                final PackageParser.Package pkg = mPackages.get(pkgName);
6982                result = null;
6983                if (pkg != null) {
6984                    result = filterIfNotSystemUser(
6985                            mActivities.queryIntentForPackage(
6986                                    intent, resolvedType, flags, pkg.activities, userId),
6987                            userId);
6988                }
6989                if (result == null || result.size() == 0) {
6990                    // the caller wants to resolve for a particular package; however, there
6991                    // were no installed results, so, try to find an ephemeral result
6992                    addEphemeral = !ephemeralDisabled
6993                            && isInstantAppAllowed(
6994                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
6995                    if (result == null) {
6996                        result = new ArrayList<>();
6997                    }
6998                }
6999            }
7000        }
7001        if (addEphemeral) {
7002            result = maybeAddInstantAppInstaller(result, intent, resolvedType, flags, userId);
7003        }
7004        if (sortResult) {
7005            Collections.sort(result, mResolvePrioritySorter);
7006        }
7007        return applyPostResolutionFilter(result, instantAppPkgName);
7008    }
7009
7010    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
7011            String resolvedType, int flags, int userId) {
7012        // first, check to see if we've got an instant app already installed
7013        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
7014        ResolveInfo localInstantApp = null;
7015        boolean blockResolution = false;
7016        if (!alreadyResolvedLocally) {
7017            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
7018                    flags
7019                        | PackageManager.GET_RESOLVED_FILTER
7020                        | PackageManager.MATCH_INSTANT
7021                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
7022                    userId);
7023            for (int i = instantApps.size() - 1; i >= 0; --i) {
7024                final ResolveInfo info = instantApps.get(i);
7025                final String packageName = info.activityInfo.packageName;
7026                final PackageSetting ps = mSettings.mPackages.get(packageName);
7027                if (ps.getInstantApp(userId)) {
7028                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7029                    final int status = (int)(packedStatus >> 32);
7030                    final int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7031                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7032                        // there's a local instant application installed, but, the user has
7033                        // chosen to never use it; skip resolution and don't acknowledge
7034                        // an instant application is even available
7035                        if (DEBUG_EPHEMERAL) {
7036                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
7037                        }
7038                        blockResolution = true;
7039                        break;
7040                    } else {
7041                        // we have a locally installed instant application; skip resolution
7042                        // but acknowledge there's an instant application available
7043                        if (DEBUG_EPHEMERAL) {
7044                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
7045                        }
7046                        localInstantApp = info;
7047                        break;
7048                    }
7049                }
7050            }
7051        }
7052        // no app installed, let's see if one's available
7053        AuxiliaryResolveInfo auxiliaryResponse = null;
7054        if (!blockResolution) {
7055            if (localInstantApp == null) {
7056                // we don't have an instant app locally, resolve externally
7057                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
7058                final InstantAppRequest requestObject = new InstantAppRequest(
7059                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
7060                        null /*callingPackage*/, userId, null /*verificationBundle*/);
7061                auxiliaryResponse =
7062                        InstantAppResolver.doInstantAppResolutionPhaseOne(
7063                                mContext, mInstantAppResolverConnection, requestObject);
7064                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7065            } else {
7066                // we have an instant application locally, but, we can't admit that since
7067                // callers shouldn't be able to determine prior browsing. create a dummy
7068                // auxiliary response so the downstream code behaves as if there's an
7069                // instant application available externally. when it comes time to start
7070                // the instant application, we'll do the right thing.
7071                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
7072                auxiliaryResponse = new AuxiliaryResolveInfo(
7073                        ai.packageName, null /*splitName*/, ai.versionCode, null /*failureIntent*/);
7074            }
7075        }
7076        if (auxiliaryResponse != null) {
7077            if (DEBUG_EPHEMERAL) {
7078                Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7079            }
7080            final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
7081            final PackageSetting ps =
7082                    mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
7083            if (ps != null) {
7084                ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
7085                        mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
7086                ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
7087                ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
7088                // make sure this resolver is the default
7089                ephemeralInstaller.isDefault = true;
7090                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7091                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7092                // add a non-generic filter
7093                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
7094                ephemeralInstaller.filter.addDataPath(
7095                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
7096                ephemeralInstaller.isInstantAppAvailable = true;
7097                result.add(ephemeralInstaller);
7098            }
7099        }
7100        return result;
7101    }
7102
7103    private static class CrossProfileDomainInfo {
7104        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
7105        ResolveInfo resolveInfo;
7106        /* Best domain verification status of the activities found in the other profile */
7107        int bestDomainVerificationStatus;
7108    }
7109
7110    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
7111            String resolvedType, int flags, int sourceUserId, int parentUserId) {
7112        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
7113                sourceUserId)) {
7114            return null;
7115        }
7116        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7117                resolvedType, flags, parentUserId);
7118
7119        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
7120            return null;
7121        }
7122        CrossProfileDomainInfo result = null;
7123        int size = resultTargetUser.size();
7124        for (int i = 0; i < size; i++) {
7125            ResolveInfo riTargetUser = resultTargetUser.get(i);
7126            // Intent filter verification is only for filters that specify a host. So don't return
7127            // those that handle all web uris.
7128            if (riTargetUser.handleAllWebDataURI) {
7129                continue;
7130            }
7131            String packageName = riTargetUser.activityInfo.packageName;
7132            PackageSetting ps = mSettings.mPackages.get(packageName);
7133            if (ps == null) {
7134                continue;
7135            }
7136            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
7137            int status = (int)(verificationState >> 32);
7138            if (result == null) {
7139                result = new CrossProfileDomainInfo();
7140                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
7141                        sourceUserId, parentUserId);
7142                result.bestDomainVerificationStatus = status;
7143            } else {
7144                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
7145                        result.bestDomainVerificationStatus);
7146            }
7147        }
7148        // Don't consider matches with status NEVER across profiles.
7149        if (result != null && result.bestDomainVerificationStatus
7150                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7151            return null;
7152        }
7153        return result;
7154    }
7155
7156    /**
7157     * Verification statuses are ordered from the worse to the best, except for
7158     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
7159     */
7160    private int bestDomainVerificationStatus(int status1, int status2) {
7161        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7162            return status2;
7163        }
7164        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7165            return status1;
7166        }
7167        return (int) MathUtils.max(status1, status2);
7168    }
7169
7170    private boolean isUserEnabled(int userId) {
7171        long callingId = Binder.clearCallingIdentity();
7172        try {
7173            UserInfo userInfo = sUserManager.getUserInfo(userId);
7174            return userInfo != null && userInfo.isEnabled();
7175        } finally {
7176            Binder.restoreCallingIdentity(callingId);
7177        }
7178    }
7179
7180    /**
7181     * Filter out activities with systemUserOnly flag set, when current user is not System.
7182     *
7183     * @return filtered list
7184     */
7185    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
7186        if (userId == UserHandle.USER_SYSTEM) {
7187            return resolveInfos;
7188        }
7189        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7190            ResolveInfo info = resolveInfos.get(i);
7191            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
7192                resolveInfos.remove(i);
7193            }
7194        }
7195        return resolveInfos;
7196    }
7197
7198    /**
7199     * Filters out ephemeral activities.
7200     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
7201     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
7202     *
7203     * @param resolveInfos The pre-filtered list of resolved activities
7204     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
7205     *          is performed.
7206     * @return A filtered list of resolved activities.
7207     */
7208    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
7209            String ephemeralPkgName) {
7210        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7211            final ResolveInfo info = resolveInfos.get(i);
7212            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
7213            // TODO: When adding on-demand split support for non-instant apps, remove this check
7214            // and always apply post filtering
7215            // allow activities that are defined in the provided package
7216            if (isEphemeralApp) {
7217                if (info.activityInfo.splitName != null
7218                        && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
7219                                info.activityInfo.splitName)) {
7220                    // requested activity is defined in a split that hasn't been installed yet.
7221                    // add the installer to the resolve list
7222                    if (DEBUG_EPHEMERAL) {
7223                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7224                    }
7225                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7226                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7227                            info.activityInfo.packageName, info.activityInfo.splitName,
7228                            info.activityInfo.applicationInfo.versionCode, null /*failureIntent*/);
7229                    // make sure this resolver is the default
7230                    installerInfo.isDefault = true;
7231                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7232                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7233                    // add a non-generic filter
7234                    installerInfo.filter = new IntentFilter();
7235                    // load resources from the correct package
7236                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7237                    resolveInfos.set(i, installerInfo);
7238                    continue;
7239                }
7240            }
7241            // caller is a full app, don't need to apply any other filtering
7242            if (ephemeralPkgName == null) {
7243                continue;
7244            } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
7245                // caller is same app; don't need to apply any other filtering
7246                continue;
7247            }
7248            // allow activities that have been explicitly exposed to ephemeral apps
7249            if (!isEphemeralApp
7250                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7251                continue;
7252            }
7253            resolveInfos.remove(i);
7254        }
7255        return resolveInfos;
7256    }
7257
7258    /**
7259     * @param resolveInfos list of resolve infos in descending priority order
7260     * @return if the list contains a resolve info with non-negative priority
7261     */
7262    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
7263        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
7264    }
7265
7266    private static boolean hasWebURI(Intent intent) {
7267        if (intent.getData() == null) {
7268            return false;
7269        }
7270        final String scheme = intent.getScheme();
7271        if (TextUtils.isEmpty(scheme)) {
7272            return false;
7273        }
7274        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
7275    }
7276
7277    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
7278            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
7279            int userId) {
7280        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
7281
7282        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7283            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
7284                    candidates.size());
7285        }
7286
7287        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
7288        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
7289        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
7290        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
7291        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
7292        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
7293
7294        synchronized (mPackages) {
7295            final int count = candidates.size();
7296            // First, try to use linked apps. Partition the candidates into four lists:
7297            // one for the final results, one for the "do not use ever", one for "undefined status"
7298            // and finally one for "browser app type".
7299            for (int n=0; n<count; n++) {
7300                ResolveInfo info = candidates.get(n);
7301                String packageName = info.activityInfo.packageName;
7302                PackageSetting ps = mSettings.mPackages.get(packageName);
7303                if (ps != null) {
7304                    // Add to the special match all list (Browser use case)
7305                    if (info.handleAllWebDataURI) {
7306                        matchAllList.add(info);
7307                        continue;
7308                    }
7309                    // Try to get the status from User settings first
7310                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7311                    int status = (int)(packedStatus >> 32);
7312                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7313                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
7314                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7315                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
7316                                    + " : linkgen=" + linkGeneration);
7317                        }
7318                        // Use link-enabled generation as preferredOrder, i.e.
7319                        // prefer newly-enabled over earlier-enabled.
7320                        info.preferredOrder = linkGeneration;
7321                        alwaysList.add(info);
7322                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7323                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7324                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
7325                        }
7326                        neverList.add(info);
7327                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
7328                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7329                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
7330                        }
7331                        alwaysAskList.add(info);
7332                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
7333                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
7334                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7335                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
7336                        }
7337                        undefinedList.add(info);
7338                    }
7339                }
7340            }
7341
7342            // We'll want to include browser possibilities in a few cases
7343            boolean includeBrowser = false;
7344
7345            // First try to add the "always" resolution(s) for the current user, if any
7346            if (alwaysList.size() > 0) {
7347                result.addAll(alwaysList);
7348            } else {
7349                // Add all undefined apps as we want them to appear in the disambiguation dialog.
7350                result.addAll(undefinedList);
7351                // Maybe add one for the other profile.
7352                if (xpDomainInfo != null && (
7353                        xpDomainInfo.bestDomainVerificationStatus
7354                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
7355                    result.add(xpDomainInfo.resolveInfo);
7356                }
7357                includeBrowser = true;
7358            }
7359
7360            // The presence of any 'always ask' alternatives means we'll also offer browsers.
7361            // If there were 'always' entries their preferred order has been set, so we also
7362            // back that off to make the alternatives equivalent
7363            if (alwaysAskList.size() > 0) {
7364                for (ResolveInfo i : result) {
7365                    i.preferredOrder = 0;
7366                }
7367                result.addAll(alwaysAskList);
7368                includeBrowser = true;
7369            }
7370
7371            if (includeBrowser) {
7372                // Also add browsers (all of them or only the default one)
7373                if (DEBUG_DOMAIN_VERIFICATION) {
7374                    Slog.v(TAG, "   ...including browsers in candidate set");
7375                }
7376                if ((matchFlags & MATCH_ALL) != 0) {
7377                    result.addAll(matchAllList);
7378                } else {
7379                    // Browser/generic handling case.  If there's a default browser, go straight
7380                    // to that (but only if there is no other higher-priority match).
7381                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7382                    int maxMatchPrio = 0;
7383                    ResolveInfo defaultBrowserMatch = null;
7384                    final int numCandidates = matchAllList.size();
7385                    for (int n = 0; n < numCandidates; n++) {
7386                        ResolveInfo info = matchAllList.get(n);
7387                        // track the highest overall match priority...
7388                        if (info.priority > maxMatchPrio) {
7389                            maxMatchPrio = info.priority;
7390                        }
7391                        // ...and the highest-priority default browser match
7392                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7393                            if (defaultBrowserMatch == null
7394                                    || (defaultBrowserMatch.priority < info.priority)) {
7395                                if (debug) {
7396                                    Slog.v(TAG, "Considering default browser match " + info);
7397                                }
7398                                defaultBrowserMatch = info;
7399                            }
7400                        }
7401                    }
7402                    if (defaultBrowserMatch != null
7403                            && defaultBrowserMatch.priority >= maxMatchPrio
7404                            && !TextUtils.isEmpty(defaultBrowserPackageName))
7405                    {
7406                        if (debug) {
7407                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7408                        }
7409                        result.add(defaultBrowserMatch);
7410                    } else {
7411                        result.addAll(matchAllList);
7412                    }
7413                }
7414
7415                // If there is nothing selected, add all candidates and remove the ones that the user
7416                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7417                if (result.size() == 0) {
7418                    result.addAll(candidates);
7419                    result.removeAll(neverList);
7420                }
7421            }
7422        }
7423        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7424            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7425                    result.size());
7426            for (ResolveInfo info : result) {
7427                Slog.v(TAG, "  + " + info.activityInfo);
7428            }
7429        }
7430        return result;
7431    }
7432
7433    // Returns a packed value as a long:
7434    //
7435    // high 'int'-sized word: link status: undefined/ask/never/always.
7436    // low 'int'-sized word: relative priority among 'always' results.
7437    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7438        long result = ps.getDomainVerificationStatusForUser(userId);
7439        // if none available, get the master status
7440        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7441            if (ps.getIntentFilterVerificationInfo() != null) {
7442                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7443            }
7444        }
7445        return result;
7446    }
7447
7448    private ResolveInfo querySkipCurrentProfileIntents(
7449            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7450            int flags, int sourceUserId) {
7451        if (matchingFilters != null) {
7452            int size = matchingFilters.size();
7453            for (int i = 0; i < size; i ++) {
7454                CrossProfileIntentFilter filter = matchingFilters.get(i);
7455                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7456                    // Checking if there are activities in the target user that can handle the
7457                    // intent.
7458                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7459                            resolvedType, flags, sourceUserId);
7460                    if (resolveInfo != null) {
7461                        return resolveInfo;
7462                    }
7463                }
7464            }
7465        }
7466        return null;
7467    }
7468
7469    // Return matching ResolveInfo in target user if any.
7470    private ResolveInfo queryCrossProfileIntents(
7471            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7472            int flags, int sourceUserId, boolean matchInCurrentProfile) {
7473        if (matchingFilters != null) {
7474            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7475            // match the same intent. For performance reasons, it is better not to
7476            // run queryIntent twice for the same userId
7477            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7478            int size = matchingFilters.size();
7479            for (int i = 0; i < size; i++) {
7480                CrossProfileIntentFilter filter = matchingFilters.get(i);
7481                int targetUserId = filter.getTargetUserId();
7482                boolean skipCurrentProfile =
7483                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7484                boolean skipCurrentProfileIfNoMatchFound =
7485                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7486                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7487                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7488                    // Checking if there are activities in the target user that can handle the
7489                    // intent.
7490                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7491                            resolvedType, flags, sourceUserId);
7492                    if (resolveInfo != null) return resolveInfo;
7493                    alreadyTriedUserIds.put(targetUserId, true);
7494                }
7495            }
7496        }
7497        return null;
7498    }
7499
7500    /**
7501     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7502     * will forward the intent to the filter's target user.
7503     * Otherwise, returns null.
7504     */
7505    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7506            String resolvedType, int flags, int sourceUserId) {
7507        int targetUserId = filter.getTargetUserId();
7508        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7509                resolvedType, flags, targetUserId);
7510        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7511            // If all the matches in the target profile are suspended, return null.
7512            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7513                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7514                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7515                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7516                            targetUserId);
7517                }
7518            }
7519        }
7520        return null;
7521    }
7522
7523    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7524            int sourceUserId, int targetUserId) {
7525        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7526        long ident = Binder.clearCallingIdentity();
7527        boolean targetIsProfile;
7528        try {
7529            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7530        } finally {
7531            Binder.restoreCallingIdentity(ident);
7532        }
7533        String className;
7534        if (targetIsProfile) {
7535            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7536        } else {
7537            className = FORWARD_INTENT_TO_PARENT;
7538        }
7539        ComponentName forwardingActivityComponentName = new ComponentName(
7540                mAndroidApplication.packageName, className);
7541        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7542                sourceUserId);
7543        if (!targetIsProfile) {
7544            forwardingActivityInfo.showUserIcon = targetUserId;
7545            forwardingResolveInfo.noResourceId = true;
7546        }
7547        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7548        forwardingResolveInfo.priority = 0;
7549        forwardingResolveInfo.preferredOrder = 0;
7550        forwardingResolveInfo.match = 0;
7551        forwardingResolveInfo.isDefault = true;
7552        forwardingResolveInfo.filter = filter;
7553        forwardingResolveInfo.targetUserId = targetUserId;
7554        return forwardingResolveInfo;
7555    }
7556
7557    @Override
7558    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7559            Intent[] specifics, String[] specificTypes, Intent intent,
7560            String resolvedType, int flags, int userId) {
7561        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7562                specificTypes, intent, resolvedType, flags, userId));
7563    }
7564
7565    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7566            Intent[] specifics, String[] specificTypes, Intent intent,
7567            String resolvedType, int flags, int userId) {
7568        if (!sUserManager.exists(userId)) return Collections.emptyList();
7569        final int callingUid = Binder.getCallingUid();
7570        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7571                false /*includeInstantApps*/);
7572        enforceCrossUserPermission(callingUid, userId,
7573                false /*requireFullPermission*/, false /*checkShell*/,
7574                "query intent activity options");
7575        final String resultsAction = intent.getAction();
7576
7577        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7578                | PackageManager.GET_RESOLVED_FILTER, userId);
7579
7580        if (DEBUG_INTENT_MATCHING) {
7581            Log.v(TAG, "Query " + intent + ": " + results);
7582        }
7583
7584        int specificsPos = 0;
7585        int N;
7586
7587        // todo: note that the algorithm used here is O(N^2).  This
7588        // isn't a problem in our current environment, but if we start running
7589        // into situations where we have more than 5 or 10 matches then this
7590        // should probably be changed to something smarter...
7591
7592        // First we go through and resolve each of the specific items
7593        // that were supplied, taking care of removing any corresponding
7594        // duplicate items in the generic resolve list.
7595        if (specifics != null) {
7596            for (int i=0; i<specifics.length; i++) {
7597                final Intent sintent = specifics[i];
7598                if (sintent == null) {
7599                    continue;
7600                }
7601
7602                if (DEBUG_INTENT_MATCHING) {
7603                    Log.v(TAG, "Specific #" + i + ": " + sintent);
7604                }
7605
7606                String action = sintent.getAction();
7607                if (resultsAction != null && resultsAction.equals(action)) {
7608                    // If this action was explicitly requested, then don't
7609                    // remove things that have it.
7610                    action = null;
7611                }
7612
7613                ResolveInfo ri = null;
7614                ActivityInfo ai = null;
7615
7616                ComponentName comp = sintent.getComponent();
7617                if (comp == null) {
7618                    ri = resolveIntent(
7619                        sintent,
7620                        specificTypes != null ? specificTypes[i] : null,
7621                            flags, userId);
7622                    if (ri == null) {
7623                        continue;
7624                    }
7625                    if (ri == mResolveInfo) {
7626                        // ACK!  Must do something better with this.
7627                    }
7628                    ai = ri.activityInfo;
7629                    comp = new ComponentName(ai.applicationInfo.packageName,
7630                            ai.name);
7631                } else {
7632                    ai = getActivityInfo(comp, flags, userId);
7633                    if (ai == null) {
7634                        continue;
7635                    }
7636                }
7637
7638                // Look for any generic query activities that are duplicates
7639                // of this specific one, and remove them from the results.
7640                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
7641                N = results.size();
7642                int j;
7643                for (j=specificsPos; j<N; j++) {
7644                    ResolveInfo sri = results.get(j);
7645                    if ((sri.activityInfo.name.equals(comp.getClassName())
7646                            && sri.activityInfo.applicationInfo.packageName.equals(
7647                                    comp.getPackageName()))
7648                        || (action != null && sri.filter.matchAction(action))) {
7649                        results.remove(j);
7650                        if (DEBUG_INTENT_MATCHING) Log.v(
7651                            TAG, "Removing duplicate item from " + j
7652                            + " due to specific " + specificsPos);
7653                        if (ri == null) {
7654                            ri = sri;
7655                        }
7656                        j--;
7657                        N--;
7658                    }
7659                }
7660
7661                // Add this specific item to its proper place.
7662                if (ri == null) {
7663                    ri = new ResolveInfo();
7664                    ri.activityInfo = ai;
7665                }
7666                results.add(specificsPos, ri);
7667                ri.specificIndex = i;
7668                specificsPos++;
7669            }
7670        }
7671
7672        // Now we go through the remaining generic results and remove any
7673        // duplicate actions that are found here.
7674        N = results.size();
7675        for (int i=specificsPos; i<N-1; i++) {
7676            final ResolveInfo rii = results.get(i);
7677            if (rii.filter == null) {
7678                continue;
7679            }
7680
7681            // Iterate over all of the actions of this result's intent
7682            // filter...  typically this should be just one.
7683            final Iterator<String> it = rii.filter.actionsIterator();
7684            if (it == null) {
7685                continue;
7686            }
7687            while (it.hasNext()) {
7688                final String action = it.next();
7689                if (resultsAction != null && resultsAction.equals(action)) {
7690                    // If this action was explicitly requested, then don't
7691                    // remove things that have it.
7692                    continue;
7693                }
7694                for (int j=i+1; j<N; j++) {
7695                    final ResolveInfo rij = results.get(j);
7696                    if (rij.filter != null && rij.filter.hasAction(action)) {
7697                        results.remove(j);
7698                        if (DEBUG_INTENT_MATCHING) Log.v(
7699                            TAG, "Removing duplicate item from " + j
7700                            + " due to action " + action + " at " + i);
7701                        j--;
7702                        N--;
7703                    }
7704                }
7705            }
7706
7707            // If the caller didn't request filter information, drop it now
7708            // so we don't have to marshall/unmarshall it.
7709            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7710                rii.filter = null;
7711            }
7712        }
7713
7714        // Filter out the caller activity if so requested.
7715        if (caller != null) {
7716            N = results.size();
7717            for (int i=0; i<N; i++) {
7718                ActivityInfo ainfo = results.get(i).activityInfo;
7719                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
7720                        && caller.getClassName().equals(ainfo.name)) {
7721                    results.remove(i);
7722                    break;
7723                }
7724            }
7725        }
7726
7727        // If the caller didn't request filter information,
7728        // drop them now so we don't have to
7729        // marshall/unmarshall it.
7730        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7731            N = results.size();
7732            for (int i=0; i<N; i++) {
7733                results.get(i).filter = null;
7734            }
7735        }
7736
7737        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
7738        return results;
7739    }
7740
7741    @Override
7742    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
7743            String resolvedType, int flags, int userId) {
7744        return new ParceledListSlice<>(
7745                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
7746    }
7747
7748    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
7749            String resolvedType, int flags, int userId) {
7750        if (!sUserManager.exists(userId)) return Collections.emptyList();
7751        final int callingUid = Binder.getCallingUid();
7752        enforceCrossUserPermission(callingUid, userId,
7753                false /*requireFullPermission*/, false /*checkShell*/,
7754                "query intent receivers");
7755        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7756        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7757                false /*includeInstantApps*/);
7758        ComponentName comp = intent.getComponent();
7759        if (comp == null) {
7760            if (intent.getSelector() != null) {
7761                intent = intent.getSelector();
7762                comp = intent.getComponent();
7763            }
7764        }
7765        if (comp != null) {
7766            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7767            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
7768            if (ai != null) {
7769                // When specifying an explicit component, we prevent the activity from being
7770                // used when either 1) the calling package is normal and the activity is within
7771                // an instant application or 2) the calling package is ephemeral and the
7772                // activity is not visible to instant applications.
7773                final boolean matchInstantApp =
7774                        (flags & PackageManager.MATCH_INSTANT) != 0;
7775                final boolean matchVisibleToInstantAppOnly =
7776                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7777                final boolean matchExplicitlyVisibleOnly =
7778                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7779                final boolean isCallerInstantApp =
7780                        instantAppPkgName != null;
7781                final boolean isTargetSameInstantApp =
7782                        comp.getPackageName().equals(instantAppPkgName);
7783                final boolean isTargetInstantApp =
7784                        (ai.applicationInfo.privateFlags
7785                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7786                final boolean isTargetVisibleToInstantApp =
7787                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7788                final boolean isTargetExplicitlyVisibleToInstantApp =
7789                        isTargetVisibleToInstantApp
7790                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7791                final boolean isTargetHiddenFromInstantApp =
7792                        !isTargetVisibleToInstantApp
7793                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7794                final boolean blockResolution =
7795                        !isTargetSameInstantApp
7796                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7797                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7798                                        && isTargetHiddenFromInstantApp));
7799                if (!blockResolution) {
7800                    ResolveInfo ri = new ResolveInfo();
7801                    ri.activityInfo = ai;
7802                    list.add(ri);
7803                }
7804            }
7805            return applyPostResolutionFilter(list, instantAppPkgName);
7806        }
7807
7808        // reader
7809        synchronized (mPackages) {
7810            String pkgName = intent.getPackage();
7811            if (pkgName == null) {
7812                final List<ResolveInfo> result =
7813                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
7814                return applyPostResolutionFilter(result, instantAppPkgName);
7815            }
7816            final PackageParser.Package pkg = mPackages.get(pkgName);
7817            if (pkg != null) {
7818                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
7819                        intent, resolvedType, flags, pkg.receivers, userId);
7820                return applyPostResolutionFilter(result, instantAppPkgName);
7821            }
7822            return Collections.emptyList();
7823        }
7824    }
7825
7826    @Override
7827    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7828        final int callingUid = Binder.getCallingUid();
7829        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
7830    }
7831
7832    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
7833            int userId, int callingUid) {
7834        if (!sUserManager.exists(userId)) return null;
7835        flags = updateFlagsForResolve(
7836                flags, userId, intent, callingUid, false /*includeInstantApps*/);
7837        List<ResolveInfo> query = queryIntentServicesInternal(
7838                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
7839        if (query != null) {
7840            if (query.size() >= 1) {
7841                // If there is more than one service with the same priority,
7842                // just arbitrarily pick the first one.
7843                return query.get(0);
7844            }
7845        }
7846        return null;
7847    }
7848
7849    @Override
7850    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7851            String resolvedType, int flags, int userId) {
7852        final int callingUid = Binder.getCallingUid();
7853        return new ParceledListSlice<>(queryIntentServicesInternal(
7854                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
7855    }
7856
7857    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7858            String resolvedType, int flags, int userId, int callingUid,
7859            boolean includeInstantApps) {
7860        if (!sUserManager.exists(userId)) return Collections.emptyList();
7861        enforceCrossUserPermission(callingUid, userId,
7862                false /*requireFullPermission*/, false /*checkShell*/,
7863                "query intent receivers");
7864        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7865        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7866        ComponentName comp = intent.getComponent();
7867        if (comp == null) {
7868            if (intent.getSelector() != null) {
7869                intent = intent.getSelector();
7870                comp = intent.getComponent();
7871            }
7872        }
7873        if (comp != null) {
7874            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7875            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7876            if (si != null) {
7877                // When specifying an explicit component, we prevent the service from being
7878                // used when either 1) the service is in an instant application and the
7879                // caller is not the same instant application or 2) the calling package is
7880                // ephemeral and the activity is not visible to ephemeral applications.
7881                final boolean matchInstantApp =
7882                        (flags & PackageManager.MATCH_INSTANT) != 0;
7883                final boolean matchVisibleToInstantAppOnly =
7884                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7885                final boolean isCallerInstantApp =
7886                        instantAppPkgName != null;
7887                final boolean isTargetSameInstantApp =
7888                        comp.getPackageName().equals(instantAppPkgName);
7889                final boolean isTargetInstantApp =
7890                        (si.applicationInfo.privateFlags
7891                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7892                final boolean isTargetHiddenFromInstantApp =
7893                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7894                final boolean blockResolution =
7895                        !isTargetSameInstantApp
7896                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7897                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7898                                        && isTargetHiddenFromInstantApp));
7899                if (!blockResolution) {
7900                    final ResolveInfo ri = new ResolveInfo();
7901                    ri.serviceInfo = si;
7902                    list.add(ri);
7903                }
7904            }
7905            return list;
7906        }
7907
7908        // reader
7909        synchronized (mPackages) {
7910            String pkgName = intent.getPackage();
7911            if (pkgName == null) {
7912                return applyPostServiceResolutionFilter(
7913                        mServices.queryIntent(intent, resolvedType, flags, userId),
7914                        instantAppPkgName);
7915            }
7916            final PackageParser.Package pkg = mPackages.get(pkgName);
7917            if (pkg != null) {
7918                return applyPostServiceResolutionFilter(
7919                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7920                                userId),
7921                        instantAppPkgName);
7922            }
7923            return Collections.emptyList();
7924        }
7925    }
7926
7927    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
7928            String instantAppPkgName) {
7929        // TODO: When adding on-demand split support for non-instant apps, remove this check
7930        // and always apply post filtering
7931        if (instantAppPkgName == null) {
7932            return resolveInfos;
7933        }
7934        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7935            final ResolveInfo info = resolveInfos.get(i);
7936            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
7937            // allow services that are defined in the provided package
7938            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
7939                if (info.serviceInfo.splitName != null
7940                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
7941                                info.serviceInfo.splitName)) {
7942                    // requested service is defined in a split that hasn't been installed yet.
7943                    // add the installer to the resolve list
7944                    if (DEBUG_EPHEMERAL) {
7945                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7946                    }
7947                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7948                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7949                            info.serviceInfo.packageName, info.serviceInfo.splitName,
7950                            info.serviceInfo.applicationInfo.versionCode, null /*failureIntent*/);
7951                    // make sure this resolver is the default
7952                    installerInfo.isDefault = true;
7953                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7954                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7955                    // add a non-generic filter
7956                    installerInfo.filter = new IntentFilter();
7957                    // load resources from the correct package
7958                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7959                    resolveInfos.set(i, installerInfo);
7960                }
7961                continue;
7962            }
7963            // allow services that have been explicitly exposed to ephemeral apps
7964            if (!isEphemeralApp
7965                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7966                continue;
7967            }
7968            resolveInfos.remove(i);
7969        }
7970        return resolveInfos;
7971    }
7972
7973    @Override
7974    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7975            String resolvedType, int flags, int userId) {
7976        return new ParceledListSlice<>(
7977                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7978    }
7979
7980    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7981            Intent intent, String resolvedType, int flags, int userId) {
7982        if (!sUserManager.exists(userId)) return Collections.emptyList();
7983        final int callingUid = Binder.getCallingUid();
7984        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7985        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7986                false /*includeInstantApps*/);
7987        ComponentName comp = intent.getComponent();
7988        if (comp == null) {
7989            if (intent.getSelector() != null) {
7990                intent = intent.getSelector();
7991                comp = intent.getComponent();
7992            }
7993        }
7994        if (comp != null) {
7995            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7996            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
7997            if (pi != null) {
7998                // When specifying an explicit component, we prevent the provider from being
7999                // used when either 1) the provider is in an instant application and the
8000                // caller is not the same instant application or 2) the calling package is an
8001                // instant application and the provider is not visible to instant applications.
8002                final boolean matchInstantApp =
8003                        (flags & PackageManager.MATCH_INSTANT) != 0;
8004                final boolean matchVisibleToInstantAppOnly =
8005                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8006                final boolean isCallerInstantApp =
8007                        instantAppPkgName != null;
8008                final boolean isTargetSameInstantApp =
8009                        comp.getPackageName().equals(instantAppPkgName);
8010                final boolean isTargetInstantApp =
8011                        (pi.applicationInfo.privateFlags
8012                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8013                final boolean isTargetHiddenFromInstantApp =
8014                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
8015                final boolean blockResolution =
8016                        !isTargetSameInstantApp
8017                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8018                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
8019                                        && isTargetHiddenFromInstantApp));
8020                if (!blockResolution) {
8021                    final ResolveInfo ri = new ResolveInfo();
8022                    ri.providerInfo = pi;
8023                    list.add(ri);
8024                }
8025            }
8026            return list;
8027        }
8028
8029        // reader
8030        synchronized (mPackages) {
8031            String pkgName = intent.getPackage();
8032            if (pkgName == null) {
8033                return applyPostContentProviderResolutionFilter(
8034                        mProviders.queryIntent(intent, resolvedType, flags, userId),
8035                        instantAppPkgName);
8036            }
8037            final PackageParser.Package pkg = mPackages.get(pkgName);
8038            if (pkg != null) {
8039                return applyPostContentProviderResolutionFilter(
8040                        mProviders.queryIntentForPackage(
8041                        intent, resolvedType, flags, pkg.providers, userId),
8042                        instantAppPkgName);
8043            }
8044            return Collections.emptyList();
8045        }
8046    }
8047
8048    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
8049            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
8050        // TODO: When adding on-demand split support for non-instant applications, remove
8051        // this check and always apply post filtering
8052        if (instantAppPkgName == null) {
8053            return resolveInfos;
8054        }
8055        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
8056            final ResolveInfo info = resolveInfos.get(i);
8057            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
8058            // allow providers that are defined in the provided package
8059            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
8060                if (info.providerInfo.splitName != null
8061                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
8062                                info.providerInfo.splitName)) {
8063                    // requested provider is defined in a split that hasn't been installed yet.
8064                    // add the installer to the resolve list
8065                    if (DEBUG_EPHEMERAL) {
8066                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
8067                    }
8068                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
8069                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
8070                            info.providerInfo.packageName, info.providerInfo.splitName,
8071                            info.providerInfo.applicationInfo.versionCode, null /*failureIntent*/);
8072                    // make sure this resolver is the default
8073                    installerInfo.isDefault = true;
8074                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
8075                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
8076                    // add a non-generic filter
8077                    installerInfo.filter = new IntentFilter();
8078                    // load resources from the correct package
8079                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
8080                    resolveInfos.set(i, installerInfo);
8081                }
8082                continue;
8083            }
8084            // allow providers that have been explicitly exposed to instant applications
8085            if (!isEphemeralApp
8086                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
8087                continue;
8088            }
8089            resolveInfos.remove(i);
8090        }
8091        return resolveInfos;
8092    }
8093
8094    @Override
8095    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
8096        final int callingUid = Binder.getCallingUid();
8097        if (getInstantAppPackageName(callingUid) != null) {
8098            return ParceledListSlice.emptyList();
8099        }
8100        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8101        flags = updateFlagsForPackage(flags, userId, null);
8102        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8103        enforceCrossUserPermission(callingUid, userId,
8104                true /* requireFullPermission */, false /* checkShell */,
8105                "get installed packages");
8106
8107        // writer
8108        synchronized (mPackages) {
8109            ArrayList<PackageInfo> list;
8110            if (listUninstalled) {
8111                list = new ArrayList<>(mSettings.mPackages.size());
8112                for (PackageSetting ps : mSettings.mPackages.values()) {
8113                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8114                        continue;
8115                    }
8116                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8117                        return null;
8118                    }
8119                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8120                    if (pi != null) {
8121                        list.add(pi);
8122                    }
8123                }
8124            } else {
8125                list = new ArrayList<>(mPackages.size());
8126                for (PackageParser.Package p : mPackages.values()) {
8127                    final PackageSetting ps = (PackageSetting) p.mExtras;
8128                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8129                        continue;
8130                    }
8131                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8132                        return null;
8133                    }
8134                    final PackageInfo pi = generatePackageInfo((PackageSetting)
8135                            p.mExtras, flags, userId);
8136                    if (pi != null) {
8137                        list.add(pi);
8138                    }
8139                }
8140            }
8141
8142            return new ParceledListSlice<>(list);
8143        }
8144    }
8145
8146    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
8147            String[] permissions, boolean[] tmp, int flags, int userId) {
8148        int numMatch = 0;
8149        final PermissionsState permissionsState = ps.getPermissionsState();
8150        for (int i=0; i<permissions.length; i++) {
8151            final String permission = permissions[i];
8152            if (permissionsState.hasPermission(permission, userId)) {
8153                tmp[i] = true;
8154                numMatch++;
8155            } else {
8156                tmp[i] = false;
8157            }
8158        }
8159        if (numMatch == 0) {
8160            return;
8161        }
8162        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8163
8164        // The above might return null in cases of uninstalled apps or install-state
8165        // skew across users/profiles.
8166        if (pi != null) {
8167            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
8168                if (numMatch == permissions.length) {
8169                    pi.requestedPermissions = permissions;
8170                } else {
8171                    pi.requestedPermissions = new String[numMatch];
8172                    numMatch = 0;
8173                    for (int i=0; i<permissions.length; i++) {
8174                        if (tmp[i]) {
8175                            pi.requestedPermissions[numMatch] = permissions[i];
8176                            numMatch++;
8177                        }
8178                    }
8179                }
8180            }
8181            list.add(pi);
8182        }
8183    }
8184
8185    @Override
8186    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
8187            String[] permissions, int flags, int userId) {
8188        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8189        flags = updateFlagsForPackage(flags, userId, permissions);
8190        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8191                true /* requireFullPermission */, false /* checkShell */,
8192                "get packages holding permissions");
8193        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8194
8195        // writer
8196        synchronized (mPackages) {
8197            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
8198            boolean[] tmpBools = new boolean[permissions.length];
8199            if (listUninstalled) {
8200                for (PackageSetting ps : mSettings.mPackages.values()) {
8201                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8202                            userId);
8203                }
8204            } else {
8205                for (PackageParser.Package pkg : mPackages.values()) {
8206                    PackageSetting ps = (PackageSetting)pkg.mExtras;
8207                    if (ps != null) {
8208                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8209                                userId);
8210                    }
8211                }
8212            }
8213
8214            return new ParceledListSlice<PackageInfo>(list);
8215        }
8216    }
8217
8218    @Override
8219    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
8220        final int callingUid = Binder.getCallingUid();
8221        if (getInstantAppPackageName(callingUid) != null) {
8222            return ParceledListSlice.emptyList();
8223        }
8224        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8225        flags = updateFlagsForApplication(flags, userId, null);
8226        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8227
8228        // writer
8229        synchronized (mPackages) {
8230            ArrayList<ApplicationInfo> list;
8231            if (listUninstalled) {
8232                list = new ArrayList<>(mSettings.mPackages.size());
8233                for (PackageSetting ps : mSettings.mPackages.values()) {
8234                    ApplicationInfo ai;
8235                    int effectiveFlags = flags;
8236                    if (ps.isSystem()) {
8237                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
8238                    }
8239                    if (ps.pkg != null) {
8240                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8241                            continue;
8242                        }
8243                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8244                            return null;
8245                        }
8246                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
8247                                ps.readUserState(userId), userId);
8248                        if (ai != null) {
8249                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
8250                        }
8251                    } else {
8252                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
8253                        // and already converts to externally visible package name
8254                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
8255                                callingUid, effectiveFlags, userId);
8256                    }
8257                    if (ai != null) {
8258                        list.add(ai);
8259                    }
8260                }
8261            } else {
8262                list = new ArrayList<>(mPackages.size());
8263                for (PackageParser.Package p : mPackages.values()) {
8264                    if (p.mExtras != null) {
8265                        PackageSetting ps = (PackageSetting) p.mExtras;
8266                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
8267                            continue;
8268                        }
8269                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8270                            return null;
8271                        }
8272                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8273                                ps.readUserState(userId), userId);
8274                        if (ai != null) {
8275                            ai.packageName = resolveExternalPackageNameLPr(p);
8276                            list.add(ai);
8277                        }
8278                    }
8279                }
8280            }
8281
8282            return new ParceledListSlice<>(list);
8283        }
8284    }
8285
8286    @Override
8287    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
8288        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8289            return null;
8290        }
8291        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8292                "getEphemeralApplications");
8293        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8294                true /* requireFullPermission */, false /* checkShell */,
8295                "getEphemeralApplications");
8296        synchronized (mPackages) {
8297            List<InstantAppInfo> instantApps = mInstantAppRegistry
8298                    .getInstantAppsLPr(userId);
8299            if (instantApps != null) {
8300                return new ParceledListSlice<>(instantApps);
8301            }
8302        }
8303        return null;
8304    }
8305
8306    @Override
8307    public boolean isInstantApp(String packageName, int userId) {
8308        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8309                true /* requireFullPermission */, false /* checkShell */,
8310                "isInstantApp");
8311        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8312            return false;
8313        }
8314
8315        synchronized (mPackages) {
8316            int callingUid = Binder.getCallingUid();
8317            if (Process.isIsolated(callingUid)) {
8318                callingUid = mIsolatedOwners.get(callingUid);
8319            }
8320            final PackageSetting ps = mSettings.mPackages.get(packageName);
8321            PackageParser.Package pkg = mPackages.get(packageName);
8322            final boolean returnAllowed =
8323                    ps != null
8324                    && (isCallerSameApp(packageName, callingUid)
8325                            || canViewInstantApps(callingUid, userId)
8326                            || mInstantAppRegistry.isInstantAccessGranted(
8327                                    userId, UserHandle.getAppId(callingUid), ps.appId));
8328            if (returnAllowed) {
8329                return ps.getInstantApp(userId);
8330            }
8331        }
8332        return false;
8333    }
8334
8335    @Override
8336    public byte[] getInstantAppCookie(String packageName, int userId) {
8337        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8338            return null;
8339        }
8340
8341        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8342                true /* requireFullPermission */, false /* checkShell */,
8343                "getInstantAppCookie");
8344        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8345            return null;
8346        }
8347        synchronized (mPackages) {
8348            return mInstantAppRegistry.getInstantAppCookieLPw(
8349                    packageName, userId);
8350        }
8351    }
8352
8353    @Override
8354    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8355        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8356            return true;
8357        }
8358
8359        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8360                true /* requireFullPermission */, true /* checkShell */,
8361                "setInstantAppCookie");
8362        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8363            return false;
8364        }
8365        synchronized (mPackages) {
8366            return mInstantAppRegistry.setInstantAppCookieLPw(
8367                    packageName, cookie, userId);
8368        }
8369    }
8370
8371    @Override
8372    public Bitmap getInstantAppIcon(String packageName, int userId) {
8373        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8374            return null;
8375        }
8376
8377        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8378                "getInstantAppIcon");
8379
8380        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8381                true /* requireFullPermission */, false /* checkShell */,
8382                "getInstantAppIcon");
8383
8384        synchronized (mPackages) {
8385            return mInstantAppRegistry.getInstantAppIconLPw(
8386                    packageName, userId);
8387        }
8388    }
8389
8390    private boolean isCallerSameApp(String packageName, int uid) {
8391        PackageParser.Package pkg = mPackages.get(packageName);
8392        return pkg != null
8393                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8394    }
8395
8396    @Override
8397    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8398        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8399            return ParceledListSlice.emptyList();
8400        }
8401        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8402    }
8403
8404    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8405        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8406
8407        // reader
8408        synchronized (mPackages) {
8409            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8410            final int userId = UserHandle.getCallingUserId();
8411            while (i.hasNext()) {
8412                final PackageParser.Package p = i.next();
8413                if (p.applicationInfo == null) continue;
8414
8415                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8416                        && !p.applicationInfo.isDirectBootAware();
8417                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8418                        && p.applicationInfo.isDirectBootAware();
8419
8420                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8421                        && (!mSafeMode || isSystemApp(p))
8422                        && (matchesUnaware || matchesAware)) {
8423                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
8424                    if (ps != null) {
8425                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8426                                ps.readUserState(userId), userId);
8427                        if (ai != null) {
8428                            finalList.add(ai);
8429                        }
8430                    }
8431                }
8432            }
8433        }
8434
8435        return finalList;
8436    }
8437
8438    @Override
8439    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8440        if (!sUserManager.exists(userId)) return null;
8441        flags = updateFlagsForComponent(flags, userId, name);
8442        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
8443        // reader
8444        synchronized (mPackages) {
8445            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8446            PackageSetting ps = provider != null
8447                    ? mSettings.mPackages.get(provider.owner.packageName)
8448                    : null;
8449            if (ps != null) {
8450                final boolean isInstantApp = ps.getInstantApp(userId);
8451                // normal application; filter out instant application provider
8452                if (instantAppPkgName == null && isInstantApp) {
8453                    return null;
8454                }
8455                // instant application; filter out other instant applications
8456                if (instantAppPkgName != null
8457                        && isInstantApp
8458                        && !provider.owner.packageName.equals(instantAppPkgName)) {
8459                    return null;
8460                }
8461                // instant application; filter out non-exposed provider
8462                if (instantAppPkgName != null
8463                        && !isInstantApp
8464                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
8465                    return null;
8466                }
8467                // provider not enabled
8468                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8469                    return null;
8470                }
8471                return PackageParser.generateProviderInfo(
8472                        provider, flags, ps.readUserState(userId), userId);
8473            }
8474            return null;
8475        }
8476    }
8477
8478    /**
8479     * @deprecated
8480     */
8481    @Deprecated
8482    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8483        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8484            return;
8485        }
8486        // reader
8487        synchronized (mPackages) {
8488            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8489                    .entrySet().iterator();
8490            final int userId = UserHandle.getCallingUserId();
8491            while (i.hasNext()) {
8492                Map.Entry<String, PackageParser.Provider> entry = i.next();
8493                PackageParser.Provider p = entry.getValue();
8494                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8495
8496                if (ps != null && p.syncable
8497                        && (!mSafeMode || (p.info.applicationInfo.flags
8498                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8499                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8500                            ps.readUserState(userId), userId);
8501                    if (info != null) {
8502                        outNames.add(entry.getKey());
8503                        outInfo.add(info);
8504                    }
8505                }
8506            }
8507        }
8508    }
8509
8510    @Override
8511    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8512            int uid, int flags, String metaDataKey) {
8513        final int callingUid = Binder.getCallingUid();
8514        final int userId = processName != null ? UserHandle.getUserId(uid)
8515                : UserHandle.getCallingUserId();
8516        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8517        flags = updateFlagsForComponent(flags, userId, processName);
8518        ArrayList<ProviderInfo> finalList = null;
8519        // reader
8520        synchronized (mPackages) {
8521            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8522            while (i.hasNext()) {
8523                final PackageParser.Provider p = i.next();
8524                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8525                if (ps != null && p.info.authority != null
8526                        && (processName == null
8527                                || (p.info.processName.equals(processName)
8528                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8529                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8530
8531                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8532                    // parameter.
8533                    if (metaDataKey != null
8534                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8535                        continue;
8536                    }
8537                    final ComponentName component =
8538                            new ComponentName(p.info.packageName, p.info.name);
8539                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8540                        continue;
8541                    }
8542                    if (finalList == null) {
8543                        finalList = new ArrayList<ProviderInfo>(3);
8544                    }
8545                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8546                            ps.readUserState(userId), userId);
8547                    if (info != null) {
8548                        finalList.add(info);
8549                    }
8550                }
8551            }
8552        }
8553
8554        if (finalList != null) {
8555            Collections.sort(finalList, mProviderInitOrderSorter);
8556            return new ParceledListSlice<ProviderInfo>(finalList);
8557        }
8558
8559        return ParceledListSlice.emptyList();
8560    }
8561
8562    @Override
8563    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8564        // reader
8565        synchronized (mPackages) {
8566            final int callingUid = Binder.getCallingUid();
8567            final int callingUserId = UserHandle.getUserId(callingUid);
8568            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8569            if (ps == null) return null;
8570            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8571                return null;
8572            }
8573            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8574            return PackageParser.generateInstrumentationInfo(i, flags);
8575        }
8576    }
8577
8578    @Override
8579    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8580            String targetPackage, int flags) {
8581        final int callingUid = Binder.getCallingUid();
8582        final int callingUserId = UserHandle.getUserId(callingUid);
8583        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8584        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8585            return ParceledListSlice.emptyList();
8586        }
8587        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8588    }
8589
8590    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8591            int flags) {
8592        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8593
8594        // reader
8595        synchronized (mPackages) {
8596            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8597            while (i.hasNext()) {
8598                final PackageParser.Instrumentation p = i.next();
8599                if (targetPackage == null
8600                        || targetPackage.equals(p.info.targetPackage)) {
8601                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8602                            flags);
8603                    if (ii != null) {
8604                        finalList.add(ii);
8605                    }
8606                }
8607            }
8608        }
8609
8610        return finalList;
8611    }
8612
8613    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
8614        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
8615        try {
8616            scanDirLI(dir, parseFlags, scanFlags, currentTime);
8617        } finally {
8618            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8619        }
8620    }
8621
8622    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
8623        final File[] files = dir.listFiles();
8624        if (ArrayUtils.isEmpty(files)) {
8625            Log.d(TAG, "No files in app dir " + dir);
8626            return;
8627        }
8628
8629        if (DEBUG_PACKAGE_SCANNING) {
8630            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
8631                    + " flags=0x" + Integer.toHexString(parseFlags));
8632        }
8633        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
8634                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
8635                mParallelPackageParserCallback);
8636
8637        // Submit files for parsing in parallel
8638        int fileCount = 0;
8639        for (File file : files) {
8640            final boolean isPackage = (isApkFile(file) || file.isDirectory())
8641                    && !PackageInstallerService.isStageName(file.getName());
8642            if (!isPackage) {
8643                // Ignore entries which are not packages
8644                continue;
8645            }
8646            parallelPackageParser.submit(file, parseFlags);
8647            fileCount++;
8648        }
8649
8650        // Process results one by one
8651        for (; fileCount > 0; fileCount--) {
8652            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
8653            Throwable throwable = parseResult.throwable;
8654            int errorCode = PackageManager.INSTALL_SUCCEEDED;
8655
8656            if (throwable == null) {
8657                // Static shared libraries have synthetic package names
8658                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
8659                    renameStaticSharedLibraryPackage(parseResult.pkg);
8660                }
8661                try {
8662                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
8663                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
8664                                currentTime, null);
8665                    }
8666                } catch (PackageManagerException e) {
8667                    errorCode = e.error;
8668                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
8669                }
8670            } else if (throwable instanceof PackageParser.PackageParserException) {
8671                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
8672                        throwable;
8673                errorCode = e.error;
8674                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
8675            } else {
8676                throw new IllegalStateException("Unexpected exception occurred while parsing "
8677                        + parseResult.scanFile, throwable);
8678            }
8679
8680            // Delete invalid userdata apps
8681            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
8682                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
8683                logCriticalInfo(Log.WARN,
8684                        "Deleting invalid package at " + parseResult.scanFile);
8685                removeCodePathLI(parseResult.scanFile);
8686            }
8687        }
8688        parallelPackageParser.close();
8689    }
8690
8691    private static File getSettingsProblemFile() {
8692        File dataDir = Environment.getDataDirectory();
8693        File systemDir = new File(dataDir, "system");
8694        File fname = new File(systemDir, "uiderrors.txt");
8695        return fname;
8696    }
8697
8698    static void reportSettingsProblem(int priority, String msg) {
8699        logCriticalInfo(priority, msg);
8700    }
8701
8702    public static void logCriticalInfo(int priority, String msg) {
8703        Slog.println(priority, TAG, msg);
8704        EventLogTags.writePmCriticalInfo(msg);
8705        try {
8706            File fname = getSettingsProblemFile();
8707            FileOutputStream out = new FileOutputStream(fname, true);
8708            PrintWriter pw = new FastPrintWriter(out);
8709            SimpleDateFormat formatter = new SimpleDateFormat();
8710            String dateString = formatter.format(new Date(System.currentTimeMillis()));
8711            pw.println(dateString + ": " + msg);
8712            pw.close();
8713            FileUtils.setPermissions(
8714                    fname.toString(),
8715                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
8716                    -1, -1);
8717        } catch (java.io.IOException e) {
8718        }
8719    }
8720
8721    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
8722        if (srcFile.isDirectory()) {
8723            final File baseFile = new File(pkg.baseCodePath);
8724            long maxModifiedTime = baseFile.lastModified();
8725            if (pkg.splitCodePaths != null) {
8726                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
8727                    final File splitFile = new File(pkg.splitCodePaths[i]);
8728                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
8729                }
8730            }
8731            return maxModifiedTime;
8732        }
8733        return srcFile.lastModified();
8734    }
8735
8736    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
8737            final int policyFlags) throws PackageManagerException {
8738        // When upgrading from pre-N MR1, verify the package time stamp using the package
8739        // directory and not the APK file.
8740        final long lastModifiedTime = mIsPreNMR1Upgrade
8741                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
8742        if (ps != null
8743                && ps.codePath.equals(srcFile)
8744                && ps.timeStamp == lastModifiedTime
8745                && !isCompatSignatureUpdateNeeded(pkg)
8746                && !isRecoverSignatureUpdateNeeded(pkg)) {
8747            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
8748            KeySetManagerService ksms = mSettings.mKeySetManagerService;
8749            ArraySet<PublicKey> signingKs;
8750            synchronized (mPackages) {
8751                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
8752            }
8753            if (ps.signatures.mSignatures != null
8754                    && ps.signatures.mSignatures.length != 0
8755                    && signingKs != null) {
8756                // Optimization: reuse the existing cached certificates
8757                // if the package appears to be unchanged.
8758                pkg.mSignatures = ps.signatures.mSignatures;
8759                pkg.mSigningKeys = signingKs;
8760                return;
8761            }
8762
8763            Slog.w(TAG, "PackageSetting for " + ps.name
8764                    + " is missing signatures.  Collecting certs again to recover them.");
8765        } else {
8766            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
8767        }
8768
8769        try {
8770            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
8771            PackageParser.collectCertificates(pkg, policyFlags);
8772        } catch (PackageParserException e) {
8773            throw PackageManagerException.from(e);
8774        } finally {
8775            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8776        }
8777    }
8778
8779    /**
8780     *  Traces a package scan.
8781     *  @see #scanPackageLI(File, int, int, long, UserHandle)
8782     */
8783    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
8784            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8785        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
8786        try {
8787            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
8788        } finally {
8789            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8790        }
8791    }
8792
8793    /**
8794     *  Scans a package and returns the newly parsed package.
8795     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
8796     */
8797    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
8798            long currentTime, UserHandle user) throws PackageManagerException {
8799        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
8800        PackageParser pp = new PackageParser();
8801        pp.setSeparateProcesses(mSeparateProcesses);
8802        pp.setOnlyCoreApps(mOnlyCore);
8803        pp.setDisplayMetrics(mMetrics);
8804        pp.setCallback(mPackageParserCallback);
8805
8806        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
8807            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
8808        }
8809
8810        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
8811        final PackageParser.Package pkg;
8812        try {
8813            pkg = pp.parsePackage(scanFile, parseFlags);
8814        } catch (PackageParserException e) {
8815            throw PackageManagerException.from(e);
8816        } finally {
8817            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8818        }
8819
8820        // Static shared libraries have synthetic package names
8821        if (pkg.applicationInfo.isStaticSharedLibrary()) {
8822            renameStaticSharedLibraryPackage(pkg);
8823        }
8824
8825        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
8826    }
8827
8828    /**
8829     *  Scans a package and returns the newly parsed package.
8830     *  @throws PackageManagerException on a parse error.
8831     */
8832    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
8833            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8834            throws PackageManagerException {
8835        // If the package has children and this is the first dive in the function
8836        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
8837        // packages (parent and children) would be successfully scanned before the
8838        // actual scan since scanning mutates internal state and we want to atomically
8839        // install the package and its children.
8840        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8841            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8842                scanFlags |= SCAN_CHECK_ONLY;
8843            }
8844        } else {
8845            scanFlags &= ~SCAN_CHECK_ONLY;
8846        }
8847
8848        // Scan the parent
8849        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
8850                scanFlags, currentTime, user);
8851
8852        // Scan the children
8853        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8854        for (int i = 0; i < childCount; i++) {
8855            PackageParser.Package childPackage = pkg.childPackages.get(i);
8856            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
8857                    currentTime, user);
8858        }
8859
8860
8861        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8862            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
8863        }
8864
8865        return scannedPkg;
8866    }
8867
8868    /**
8869     *  Scans a package and returns the newly parsed package.
8870     *  @throws PackageManagerException on a parse error.
8871     */
8872    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
8873            int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8874            throws PackageManagerException {
8875        PackageSetting ps = null;
8876        PackageSetting updatedPkg;
8877        // reader
8878        synchronized (mPackages) {
8879            // Look to see if we already know about this package.
8880            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
8881            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
8882                // This package has been renamed to its original name.  Let's
8883                // use that.
8884                ps = mSettings.getPackageLPr(oldName);
8885            }
8886            // If there was no original package, see one for the real package name.
8887            if (ps == null) {
8888                ps = mSettings.getPackageLPr(pkg.packageName);
8889            }
8890            // Check to see if this package could be hiding/updating a system
8891            // package.  Must look for it either under the original or real
8892            // package name depending on our state.
8893            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
8894            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
8895
8896            // If this is a package we don't know about on the system partition, we
8897            // may need to remove disabled child packages on the system partition
8898            // or may need to not add child packages if the parent apk is updated
8899            // on the data partition and no longer defines this child package.
8900            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
8901                // If this is a parent package for an updated system app and this system
8902                // app got an OTA update which no longer defines some of the child packages
8903                // we have to prune them from the disabled system packages.
8904                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8905                if (disabledPs != null) {
8906                    final int scannedChildCount = (pkg.childPackages != null)
8907                            ? pkg.childPackages.size() : 0;
8908                    final int disabledChildCount = disabledPs.childPackageNames != null
8909                            ? disabledPs.childPackageNames.size() : 0;
8910                    for (int i = 0; i < disabledChildCount; i++) {
8911                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
8912                        boolean disabledPackageAvailable = false;
8913                        for (int j = 0; j < scannedChildCount; j++) {
8914                            PackageParser.Package childPkg = pkg.childPackages.get(j);
8915                            if (childPkg.packageName.equals(disabledChildPackageName)) {
8916                                disabledPackageAvailable = true;
8917                                break;
8918                            }
8919                         }
8920                         if (!disabledPackageAvailable) {
8921                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
8922                         }
8923                    }
8924                }
8925            }
8926        }
8927
8928        final boolean isUpdatedPkg = updatedPkg != null;
8929        final boolean isUpdatedSystemPkg = isUpdatedPkg
8930                && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0;
8931        boolean isUpdatedPkgBetter = false;
8932        // First check if this is a system package that may involve an update
8933        if (isUpdatedSystemPkg) {
8934            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
8935            // it needs to drop FLAG_PRIVILEGED.
8936            if (locationIsPrivileged(scanFile)) {
8937                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8938            } else {
8939                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8940            }
8941
8942            if (ps != null && !ps.codePath.equals(scanFile)) {
8943                // The path has changed from what was last scanned...  check the
8944                // version of the new path against what we have stored to determine
8945                // what to do.
8946                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
8947                if (pkg.mVersionCode <= ps.versionCode) {
8948                    // The system package has been updated and the code path does not match
8949                    // Ignore entry. Skip it.
8950                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
8951                            + " ignored: updated version " + ps.versionCode
8952                            + " better than this " + pkg.mVersionCode);
8953                    if (!updatedPkg.codePath.equals(scanFile)) {
8954                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
8955                                + ps.name + " changing from " + updatedPkg.codePathString
8956                                + " to " + scanFile);
8957                        updatedPkg.codePath = scanFile;
8958                        updatedPkg.codePathString = scanFile.toString();
8959                        updatedPkg.resourcePath = scanFile;
8960                        updatedPkg.resourcePathString = scanFile.toString();
8961                    }
8962                    updatedPkg.pkg = pkg;
8963                    updatedPkg.versionCode = pkg.mVersionCode;
8964
8965                    // Update the disabled system child packages to point to the package too.
8966                    final int childCount = updatedPkg.childPackageNames != null
8967                            ? updatedPkg.childPackageNames.size() : 0;
8968                    for (int i = 0; i < childCount; i++) {
8969                        String childPackageName = updatedPkg.childPackageNames.get(i);
8970                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
8971                                childPackageName);
8972                        if (updatedChildPkg != null) {
8973                            updatedChildPkg.pkg = pkg;
8974                            updatedChildPkg.versionCode = pkg.mVersionCode;
8975                        }
8976                    }
8977                } else {
8978                    // The current app on the system partition is better than
8979                    // what we have updated to on the data partition; switch
8980                    // back to the system partition version.
8981                    // At this point, its safely assumed that package installation for
8982                    // apps in system partition will go through. If not there won't be a working
8983                    // version of the app
8984                    // writer
8985                    synchronized (mPackages) {
8986                        // Just remove the loaded entries from package lists.
8987                        mPackages.remove(ps.name);
8988                    }
8989
8990                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
8991                            + " reverting from " + ps.codePathString
8992                            + ": new version " + pkg.mVersionCode
8993                            + " better than installed " + ps.versionCode);
8994
8995                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
8996                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
8997                    synchronized (mInstallLock) {
8998                        args.cleanUpResourcesLI();
8999                    }
9000                    synchronized (mPackages) {
9001                        mSettings.enableSystemPackageLPw(ps.name);
9002                    }
9003                    isUpdatedPkgBetter = true;
9004                }
9005            }
9006        }
9007
9008        String resourcePath = null;
9009        String baseResourcePath = null;
9010        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !isUpdatedPkgBetter) {
9011            if (ps != null && ps.resourcePathString != null) {
9012                resourcePath = ps.resourcePathString;
9013                baseResourcePath = ps.resourcePathString;
9014            } else {
9015                // Should not happen at all. Just log an error.
9016                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
9017            }
9018        } else {
9019            resourcePath = pkg.codePath;
9020            baseResourcePath = pkg.baseCodePath;
9021        }
9022
9023        // Set application objects path explicitly.
9024        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
9025        pkg.setApplicationInfoCodePath(pkg.codePath);
9026        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
9027        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
9028        pkg.setApplicationInfoResourcePath(resourcePath);
9029        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
9030        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
9031
9032        // throw an exception if we have an update to a system application, but, it's not more
9033        // recent than the package we've already scanned
9034        if (isUpdatedSystemPkg && !isUpdatedPkgBetter) {
9035            throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
9036                    + scanFile + " ignored: updated version " + ps.versionCode
9037                    + " better than this " + pkg.mVersionCode);
9038        }
9039
9040        if (isUpdatedPkg) {
9041            // An updated system app will not have the PARSE_IS_SYSTEM flag set
9042            // initially
9043            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
9044
9045            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
9046            // flag set initially
9047            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
9048                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
9049            }
9050        }
9051
9052        // Verify certificates against what was last scanned
9053        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
9054
9055        /*
9056         * A new system app appeared, but we already had a non-system one of the
9057         * same name installed earlier.
9058         */
9059        boolean shouldHideSystemApp = false;
9060        if (!isUpdatedPkg && ps != null
9061                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
9062            /*
9063             * Check to make sure the signatures match first. If they don't,
9064             * wipe the installed application and its data.
9065             */
9066            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
9067                    != PackageManager.SIGNATURE_MATCH) {
9068                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
9069                        + " signatures don't match existing userdata copy; removing");
9070                try (PackageFreezer freezer = freezePackage(pkg.packageName,
9071                        "scanPackageInternalLI")) {
9072                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
9073                }
9074                ps = null;
9075            } else {
9076                /*
9077                 * If the newly-added system app is an older version than the
9078                 * already installed version, hide it. It will be scanned later
9079                 * and re-added like an update.
9080                 */
9081                if (pkg.mVersionCode <= ps.versionCode) {
9082                    shouldHideSystemApp = true;
9083                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
9084                            + " but new version " + pkg.mVersionCode + " better than installed "
9085                            + ps.versionCode + "; hiding system");
9086                } else {
9087                    /*
9088                     * The newly found system app is a newer version that the
9089                     * one previously installed. Simply remove the
9090                     * already-installed application and replace it with our own
9091                     * while keeping the application data.
9092                     */
9093                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
9094                            + " reverting from " + ps.codePathString + ": new version "
9095                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
9096                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
9097                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
9098                    synchronized (mInstallLock) {
9099                        args.cleanUpResourcesLI();
9100                    }
9101                }
9102            }
9103        }
9104
9105        // The apk is forward locked (not public) if its code and resources
9106        // are kept in different files. (except for app in either system or
9107        // vendor path).
9108        // TODO grab this value from PackageSettings
9109        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9110            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
9111                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
9112            }
9113        }
9114
9115        final int userId = ((user == null) ? 0 : user.getIdentifier());
9116        if (ps != null && ps.getInstantApp(userId)) {
9117            scanFlags |= SCAN_AS_INSTANT_APP;
9118        }
9119
9120        // Note that we invoke the following method only if we are about to unpack an application
9121        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
9122                | SCAN_UPDATE_SIGNATURE, currentTime, user);
9123
9124        /*
9125         * If the system app should be overridden by a previously installed
9126         * data, hide the system app now and let the /data/app scan pick it up
9127         * again.
9128         */
9129        if (shouldHideSystemApp) {
9130            synchronized (mPackages) {
9131                mSettings.disableSystemPackageLPw(pkg.packageName, true);
9132            }
9133        }
9134
9135        return scannedPkg;
9136    }
9137
9138    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
9139        // Derive the new package synthetic package name
9140        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
9141                + pkg.staticSharedLibVersion);
9142    }
9143
9144    private static String fixProcessName(String defProcessName,
9145            String processName) {
9146        if (processName == null) {
9147            return defProcessName;
9148        }
9149        return processName;
9150    }
9151
9152    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
9153            throws PackageManagerException {
9154        if (pkgSetting.signatures.mSignatures != null) {
9155            // Already existing package. Make sure signatures match
9156            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
9157                    == PackageManager.SIGNATURE_MATCH;
9158            if (!match) {
9159                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
9160                        == PackageManager.SIGNATURE_MATCH;
9161            }
9162            if (!match) {
9163                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
9164                        == PackageManager.SIGNATURE_MATCH;
9165            }
9166            if (!match) {
9167                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
9168                        + pkg.packageName + " signatures do not match the "
9169                        + "previously installed version; ignoring!");
9170            }
9171        }
9172
9173        // Check for shared user signatures
9174        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
9175            // Already existing package. Make sure signatures match
9176            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
9177                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
9178            if (!match) {
9179                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
9180                        == PackageManager.SIGNATURE_MATCH;
9181            }
9182            if (!match) {
9183                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
9184                        == PackageManager.SIGNATURE_MATCH;
9185            }
9186            if (!match) {
9187                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
9188                        "Package " + pkg.packageName
9189                        + " has no signatures that match those in shared user "
9190                        + pkgSetting.sharedUser.name + "; ignoring!");
9191            }
9192        }
9193    }
9194
9195    /**
9196     * Enforces that only the system UID or root's UID can call a method exposed
9197     * via Binder.
9198     *
9199     * @param message used as message if SecurityException is thrown
9200     * @throws SecurityException if the caller is not system or root
9201     */
9202    private static final void enforceSystemOrRoot(String message) {
9203        final int uid = Binder.getCallingUid();
9204        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
9205            throw new SecurityException(message);
9206        }
9207    }
9208
9209    @Override
9210    public void performFstrimIfNeeded() {
9211        enforceSystemOrRoot("Only the system can request fstrim");
9212
9213        // Before everything else, see whether we need to fstrim.
9214        try {
9215            IStorageManager sm = PackageHelper.getStorageManager();
9216            if (sm != null) {
9217                boolean doTrim = false;
9218                final long interval = android.provider.Settings.Global.getLong(
9219                        mContext.getContentResolver(),
9220                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
9221                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
9222                if (interval > 0) {
9223                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
9224                    if (timeSinceLast > interval) {
9225                        doTrim = true;
9226                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
9227                                + "; running immediately");
9228                    }
9229                }
9230                if (doTrim) {
9231                    final boolean dexOptDialogShown;
9232                    synchronized (mPackages) {
9233                        dexOptDialogShown = mDexOptDialogShown;
9234                    }
9235                    if (!isFirstBoot() && dexOptDialogShown) {
9236                        try {
9237                            ActivityManager.getService().showBootMessage(
9238                                    mContext.getResources().getString(
9239                                            R.string.android_upgrading_fstrim), true);
9240                        } catch (RemoteException e) {
9241                        }
9242                    }
9243                    sm.runMaintenance();
9244                }
9245            } else {
9246                Slog.e(TAG, "storageManager service unavailable!");
9247            }
9248        } catch (RemoteException e) {
9249            // Can't happen; StorageManagerService is local
9250        }
9251    }
9252
9253    @Override
9254    public void updatePackagesIfNeeded() {
9255        enforceSystemOrRoot("Only the system can request package update");
9256
9257        // We need to re-extract after an OTA.
9258        boolean causeUpgrade = isUpgrade();
9259
9260        // First boot or factory reset.
9261        // Note: we also handle devices that are upgrading to N right now as if it is their
9262        //       first boot, as they do not have profile data.
9263        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
9264
9265        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
9266        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
9267
9268        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
9269            return;
9270        }
9271
9272        List<PackageParser.Package> pkgs;
9273        synchronized (mPackages) {
9274            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
9275        }
9276
9277        final long startTime = System.nanoTime();
9278        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
9279                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT),
9280                    false /* bootComplete */);
9281
9282        final int elapsedTimeSeconds =
9283                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
9284
9285        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
9286        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
9287        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
9288        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
9289        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
9290    }
9291
9292    /*
9293     * Return the prebuilt profile path given a package base code path.
9294     */
9295    private static String getPrebuildProfilePath(PackageParser.Package pkg) {
9296        return pkg.baseCodePath + ".prof";
9297    }
9298
9299    /**
9300     * Performs dexopt on the set of packages in {@code packages} and returns an int array
9301     * containing statistics about the invocation. The array consists of three elements,
9302     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
9303     * and {@code numberOfPackagesFailed}.
9304     */
9305    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
9306            String compilerFilter, boolean bootComplete) {
9307
9308        int numberOfPackagesVisited = 0;
9309        int numberOfPackagesOptimized = 0;
9310        int numberOfPackagesSkipped = 0;
9311        int numberOfPackagesFailed = 0;
9312        final int numberOfPackagesToDexopt = pkgs.size();
9313
9314        for (PackageParser.Package pkg : pkgs) {
9315            numberOfPackagesVisited++;
9316
9317            if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) {
9318                // Copy over initial preopt profiles since we won't get any JIT samples for methods
9319                // that are already compiled.
9320                File profileFile = new File(getPrebuildProfilePath(pkg));
9321                // Copy profile if it exists.
9322                if (profileFile.exists()) {
9323                    try {
9324                        // We could also do this lazily before calling dexopt in
9325                        // PackageDexOptimizer to prevent this happening on first boot. The issue
9326                        // is that we don't have a good way to say "do this only once".
9327                        if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
9328                                pkg.applicationInfo.uid, pkg.packageName)) {
9329                            Log.e(TAG, "Installer failed to copy system profile!");
9330                        }
9331                    } catch (Exception e) {
9332                        Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ",
9333                                e);
9334                    }
9335                }
9336            }
9337
9338            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
9339                if (DEBUG_DEXOPT) {
9340                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
9341                }
9342                numberOfPackagesSkipped++;
9343                continue;
9344            }
9345
9346            if (DEBUG_DEXOPT) {
9347                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
9348                        numberOfPackagesToDexopt + ": " + pkg.packageName);
9349            }
9350
9351            if (showDialog) {
9352                try {
9353                    ActivityManager.getService().showBootMessage(
9354                            mContext.getResources().getString(R.string.android_upgrading_apk,
9355                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
9356                } catch (RemoteException e) {
9357                }
9358                synchronized (mPackages) {
9359                    mDexOptDialogShown = true;
9360                }
9361            }
9362
9363            // If the OTA updates a system app which was previously preopted to a non-preopted state
9364            // the app might end up being verified at runtime. That's because by default the apps
9365            // are verify-profile but for preopted apps there's no profile.
9366            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
9367            // that before the OTA the app was preopted) the app gets compiled with a non-profile
9368            // filter (by default 'quicken').
9369            // Note that at this stage unused apps are already filtered.
9370            if (isSystemApp(pkg) &&
9371                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
9372                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
9373                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
9374            }
9375
9376            // checkProfiles is false to avoid merging profiles during boot which
9377            // might interfere with background compilation (b/28612421).
9378            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
9379            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
9380            // trade-off worth doing to save boot time work.
9381            int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0;
9382            int primaryDexOptStaus = performDexOptTraced(new DexoptOptions(
9383                    pkg.packageName,
9384                    compilerFilter,
9385                    dexoptFlags));
9386
9387            if (pkg.isSystemApp()) {
9388                // Only dexopt shared secondary dex files belonging to system apps to not slow down
9389                // too much boot after an OTA.
9390                int secondaryDexoptFlags = dexoptFlags |
9391                        DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9392                        DexoptOptions.DEXOPT_ONLY_SHARED_DEX;
9393                mDexManager.dexoptSecondaryDex(new DexoptOptions(
9394                        pkg.packageName,
9395                        compilerFilter,
9396                        secondaryDexoptFlags));
9397            }
9398
9399            // TODO(shubhamajmera): Record secondary dexopt stats.
9400            switch (primaryDexOptStaus) {
9401                case PackageDexOptimizer.DEX_OPT_PERFORMED:
9402                    numberOfPackagesOptimized++;
9403                    break;
9404                case PackageDexOptimizer.DEX_OPT_SKIPPED:
9405                    numberOfPackagesSkipped++;
9406                    break;
9407                case PackageDexOptimizer.DEX_OPT_FAILED:
9408                    numberOfPackagesFailed++;
9409                    break;
9410                default:
9411                    Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus);
9412                    break;
9413            }
9414        }
9415
9416        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
9417                numberOfPackagesFailed };
9418    }
9419
9420    @Override
9421    public void notifyPackageUse(String packageName, int reason) {
9422        synchronized (mPackages) {
9423            final int callingUid = Binder.getCallingUid();
9424            final int callingUserId = UserHandle.getUserId(callingUid);
9425            if (getInstantAppPackageName(callingUid) != null) {
9426                if (!isCallerSameApp(packageName, callingUid)) {
9427                    return;
9428                }
9429            } else {
9430                if (isInstantApp(packageName, callingUserId)) {
9431                    return;
9432                }
9433            }
9434            final PackageParser.Package p = mPackages.get(packageName);
9435            if (p == null) {
9436                return;
9437            }
9438            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9439        }
9440    }
9441
9442    @Override
9443    public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) {
9444        int userId = UserHandle.getCallingUserId();
9445        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9446        if (ai == null) {
9447            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9448                + loadingPackageName + ", user=" + userId);
9449            return;
9450        }
9451        mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId);
9452    }
9453
9454    @Override
9455    public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule,
9456            IDexModuleRegisterCallback callback) {
9457        int userId = UserHandle.getCallingUserId();
9458        ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId);
9459        DexManager.RegisterDexModuleResult result;
9460        if (ai == null) {
9461            Slog.w(TAG, "Registering a dex module for a package that does not exist for the" +
9462                     " calling user. package=" + packageName + ", user=" + userId);
9463            result = new DexManager.RegisterDexModuleResult(false, "Package not installed");
9464        } else {
9465            result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId);
9466        }
9467
9468        if (callback != null) {
9469            mHandler.post(() -> {
9470                try {
9471                    callback.onDexModuleRegistered(dexModulePath, result.success, result.message);
9472                } catch (RemoteException e) {
9473                    Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e);
9474                }
9475            });
9476        }
9477    }
9478
9479    /**
9480     * Ask the package manager to perform a dex-opt with the given compiler filter.
9481     *
9482     * Note: exposed only for the shell command to allow moving packages explicitly to a
9483     *       definite state.
9484     */
9485    @Override
9486    public boolean performDexOptMode(String packageName,
9487            boolean checkProfiles, String targetCompilerFilter, boolean force,
9488            boolean bootComplete, String splitName) {
9489        int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) |
9490                (force ? DexoptOptions.DEXOPT_FORCE : 0) |
9491                (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0);
9492        return performDexOpt(new DexoptOptions(packageName, targetCompilerFilter,
9493                splitName, flags));
9494    }
9495
9496    /**
9497     * Ask the package manager to perform a dex-opt with the given compiler filter on the
9498     * secondary dex files belonging to the given package.
9499     *
9500     * Note: exposed only for the shell command to allow moving packages explicitly to a
9501     *       definite state.
9502     */
9503    @Override
9504    public boolean performDexOptSecondary(String packageName, String compilerFilter,
9505            boolean force) {
9506        int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9507                DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES |
9508                DexoptOptions.DEXOPT_BOOT_COMPLETE |
9509                (force ? DexoptOptions.DEXOPT_FORCE : 0);
9510        return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags));
9511    }
9512
9513    /*package*/ boolean performDexOpt(DexoptOptions options) {
9514        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9515            return false;
9516        } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) {
9517            return false;
9518        }
9519
9520        if (options.isDexoptOnlySecondaryDex()) {
9521            return mDexManager.dexoptSecondaryDex(options);
9522        } else {
9523            int dexoptStatus = performDexOptWithStatus(options);
9524            return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9525        }
9526    }
9527
9528    /**
9529     * Perform dexopt on the given package and return one of following result:
9530     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9531     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9532     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
9533     */
9534    /* package */ int performDexOptWithStatus(DexoptOptions options) {
9535        return performDexOptTraced(options);
9536    }
9537
9538    private int performDexOptTraced(DexoptOptions options) {
9539        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9540        try {
9541            return performDexOptInternal(options);
9542        } finally {
9543            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9544        }
9545    }
9546
9547    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
9548    // if the package can now be considered up to date for the given filter.
9549    private int performDexOptInternal(DexoptOptions options) {
9550        PackageParser.Package p;
9551        synchronized (mPackages) {
9552            p = mPackages.get(options.getPackageName());
9553            if (p == null) {
9554                // Package could not be found. Report failure.
9555                return PackageDexOptimizer.DEX_OPT_FAILED;
9556            }
9557            mPackageUsage.maybeWriteAsync(mPackages);
9558            mCompilerStats.maybeWriteAsync();
9559        }
9560        long callingId = Binder.clearCallingIdentity();
9561        try {
9562            synchronized (mInstallLock) {
9563                return performDexOptInternalWithDependenciesLI(p, options);
9564            }
9565        } finally {
9566            Binder.restoreCallingIdentity(callingId);
9567        }
9568    }
9569
9570    public ArraySet<String> getOptimizablePackages() {
9571        ArraySet<String> pkgs = new ArraySet<String>();
9572        synchronized (mPackages) {
9573            for (PackageParser.Package p : mPackages.values()) {
9574                if (PackageDexOptimizer.canOptimizePackage(p)) {
9575                    pkgs.add(p.packageName);
9576                }
9577            }
9578        }
9579        return pkgs;
9580    }
9581
9582    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
9583            DexoptOptions options) {
9584        // Select the dex optimizer based on the force parameter.
9585        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
9586        //       allocate an object here.
9587        PackageDexOptimizer pdo = options.isForce()
9588                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
9589                : mPackageDexOptimizer;
9590
9591        // Dexopt all dependencies first. Note: we ignore the return value and march on
9592        // on errors.
9593        // Note that we are going to call performDexOpt on those libraries as many times as
9594        // they are referenced in packages. When we do a batch of performDexOpt (for example
9595        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
9596        // and the first package that uses the library will dexopt it. The
9597        // others will see that the compiled code for the library is up to date.
9598        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
9599        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
9600        if (!deps.isEmpty()) {
9601            for (PackageParser.Package depPackage : deps) {
9602                // TODO: Analyze and investigate if we (should) profile libraries.
9603                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
9604                        getOrCreateCompilerPackageStats(depPackage),
9605                        true /* isUsedByOtherApps */,
9606                        options);
9607            }
9608        }
9609        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets,
9610                getOrCreateCompilerPackageStats(p),
9611                mDexManager.isUsedByOtherApps(p.packageName), options);
9612    }
9613
9614    /**
9615     * Reconcile the information we have about the secondary dex files belonging to
9616     * {@code packagName} and the actual dex files. For all dex files that were
9617     * deleted, update the internal records and delete the generated oat files.
9618     */
9619    @Override
9620    public void reconcileSecondaryDexFiles(String packageName) {
9621        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9622            return;
9623        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9624            return;
9625        }
9626        mDexManager.reconcileSecondaryDexFiles(packageName);
9627    }
9628
9629    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
9630    // a reference there.
9631    /*package*/ DexManager getDexManager() {
9632        return mDexManager;
9633    }
9634
9635    /**
9636     * Execute the background dexopt job immediately.
9637     */
9638    @Override
9639    public boolean runBackgroundDexoptJob() {
9640        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9641            return false;
9642        }
9643        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
9644    }
9645
9646    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
9647        if (p.usesLibraries != null || p.usesOptionalLibraries != null
9648                || p.usesStaticLibraries != null) {
9649            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
9650            Set<String> collectedNames = new HashSet<>();
9651            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
9652
9653            retValue.remove(p);
9654
9655            return retValue;
9656        } else {
9657            return Collections.emptyList();
9658        }
9659    }
9660
9661    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
9662            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9663        if (!collectedNames.contains(p.packageName)) {
9664            collectedNames.add(p.packageName);
9665            collected.add(p);
9666
9667            if (p.usesLibraries != null) {
9668                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
9669                        null, collected, collectedNames);
9670            }
9671            if (p.usesOptionalLibraries != null) {
9672                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
9673                        null, collected, collectedNames);
9674            }
9675            if (p.usesStaticLibraries != null) {
9676                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
9677                        p.usesStaticLibrariesVersions, collected, collectedNames);
9678            }
9679        }
9680    }
9681
9682    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
9683            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9684        final int libNameCount = libs.size();
9685        for (int i = 0; i < libNameCount; i++) {
9686            String libName = libs.get(i);
9687            int version = (versions != null && versions.length == libNameCount)
9688                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
9689            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
9690            if (libPkg != null) {
9691                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
9692            }
9693        }
9694    }
9695
9696    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
9697        synchronized (mPackages) {
9698            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
9699            if (libEntry != null) {
9700                return mPackages.get(libEntry.apk);
9701            }
9702            return null;
9703        }
9704    }
9705
9706    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
9707        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9708        if (versionedLib == null) {
9709            return null;
9710        }
9711        return versionedLib.get(version);
9712    }
9713
9714    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
9715        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9716                pkg.staticSharedLibName);
9717        if (versionedLib == null) {
9718            return null;
9719        }
9720        int previousLibVersion = -1;
9721        final int versionCount = versionedLib.size();
9722        for (int i = 0; i < versionCount; i++) {
9723            final int libVersion = versionedLib.keyAt(i);
9724            if (libVersion < pkg.staticSharedLibVersion) {
9725                previousLibVersion = Math.max(previousLibVersion, libVersion);
9726            }
9727        }
9728        if (previousLibVersion >= 0) {
9729            return versionedLib.get(previousLibVersion);
9730        }
9731        return null;
9732    }
9733
9734    public void shutdown() {
9735        mPackageUsage.writeNow(mPackages);
9736        mCompilerStats.writeNow();
9737    }
9738
9739    @Override
9740    public void dumpProfiles(String packageName) {
9741        PackageParser.Package pkg;
9742        synchronized (mPackages) {
9743            pkg = mPackages.get(packageName);
9744            if (pkg == null) {
9745                throw new IllegalArgumentException("Unknown package: " + packageName);
9746            }
9747        }
9748        /* Only the shell, root, or the app user should be able to dump profiles. */
9749        int callingUid = Binder.getCallingUid();
9750        if (callingUid != Process.SHELL_UID &&
9751            callingUid != Process.ROOT_UID &&
9752            callingUid != pkg.applicationInfo.uid) {
9753            throw new SecurityException("dumpProfiles");
9754        }
9755
9756        synchronized (mInstallLock) {
9757            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
9758            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
9759            try {
9760                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
9761                String codePaths = TextUtils.join(";", allCodePaths);
9762                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
9763            } catch (InstallerException e) {
9764                Slog.w(TAG, "Failed to dump profiles", e);
9765            }
9766            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9767        }
9768    }
9769
9770    @Override
9771    public void forceDexOpt(String packageName) {
9772        enforceSystemOrRoot("forceDexOpt");
9773
9774        PackageParser.Package pkg;
9775        synchronized (mPackages) {
9776            pkg = mPackages.get(packageName);
9777            if (pkg == null) {
9778                throw new IllegalArgumentException("Unknown package: " + packageName);
9779            }
9780        }
9781
9782        synchronized (mInstallLock) {
9783            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9784
9785            // Whoever is calling forceDexOpt wants a compiled package.
9786            // Don't use profiles since that may cause compilation to be skipped.
9787            final int res = performDexOptInternalWithDependenciesLI(
9788                    pkg,
9789                    new DexoptOptions(packageName,
9790                            getDefaultCompilerFilter(),
9791                            DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE));
9792
9793            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9794            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
9795                throw new IllegalStateException("Failed to dexopt: " + res);
9796            }
9797        }
9798    }
9799
9800    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
9801        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
9802            Slog.w(TAG, "Unable to update from " + oldPkg.name
9803                    + " to " + newPkg.packageName
9804                    + ": old package not in system partition");
9805            return false;
9806        } else if (mPackages.get(oldPkg.name) != null) {
9807            Slog.w(TAG, "Unable to update from " + oldPkg.name
9808                    + " to " + newPkg.packageName
9809                    + ": old package still exists");
9810            return false;
9811        }
9812        return true;
9813    }
9814
9815    void removeCodePathLI(File codePath) {
9816        if (codePath.isDirectory()) {
9817            try {
9818                mInstaller.rmPackageDir(codePath.getAbsolutePath());
9819            } catch (InstallerException e) {
9820                Slog.w(TAG, "Failed to remove code path", e);
9821            }
9822        } else {
9823            codePath.delete();
9824        }
9825    }
9826
9827    private int[] resolveUserIds(int userId) {
9828        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
9829    }
9830
9831    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9832        if (pkg == null) {
9833            Slog.wtf(TAG, "Package was null!", new Throwable());
9834            return;
9835        }
9836        clearAppDataLeafLIF(pkg, userId, flags);
9837        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9838        for (int i = 0; i < childCount; i++) {
9839            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9840        }
9841    }
9842
9843    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9844        final PackageSetting ps;
9845        synchronized (mPackages) {
9846            ps = mSettings.mPackages.get(pkg.packageName);
9847        }
9848        for (int realUserId : resolveUserIds(userId)) {
9849            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9850            try {
9851                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9852                        ceDataInode);
9853            } catch (InstallerException e) {
9854                Slog.w(TAG, String.valueOf(e));
9855            }
9856        }
9857    }
9858
9859    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9860        if (pkg == null) {
9861            Slog.wtf(TAG, "Package was null!", new Throwable());
9862            return;
9863        }
9864        destroyAppDataLeafLIF(pkg, userId, flags);
9865        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9866        for (int i = 0; i < childCount; i++) {
9867            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9868        }
9869    }
9870
9871    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9872        final PackageSetting ps;
9873        synchronized (mPackages) {
9874            ps = mSettings.mPackages.get(pkg.packageName);
9875        }
9876        for (int realUserId : resolveUserIds(userId)) {
9877            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9878            try {
9879                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9880                        ceDataInode);
9881            } catch (InstallerException e) {
9882                Slog.w(TAG, String.valueOf(e));
9883            }
9884            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
9885        }
9886    }
9887
9888    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
9889        if (pkg == null) {
9890            Slog.wtf(TAG, "Package was null!", new Throwable());
9891            return;
9892        }
9893        destroyAppProfilesLeafLIF(pkg);
9894        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9895        for (int i = 0; i < childCount; i++) {
9896            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
9897        }
9898    }
9899
9900    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
9901        try {
9902            mInstaller.destroyAppProfiles(pkg.packageName);
9903        } catch (InstallerException e) {
9904            Slog.w(TAG, String.valueOf(e));
9905        }
9906    }
9907
9908    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
9909        if (pkg == null) {
9910            Slog.wtf(TAG, "Package was null!", new Throwable());
9911            return;
9912        }
9913        clearAppProfilesLeafLIF(pkg);
9914        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9915        for (int i = 0; i < childCount; i++) {
9916            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
9917        }
9918    }
9919
9920    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
9921        try {
9922            mInstaller.clearAppProfiles(pkg.packageName);
9923        } catch (InstallerException e) {
9924            Slog.w(TAG, String.valueOf(e));
9925        }
9926    }
9927
9928    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
9929            long lastUpdateTime) {
9930        // Set parent install/update time
9931        PackageSetting ps = (PackageSetting) pkg.mExtras;
9932        if (ps != null) {
9933            ps.firstInstallTime = firstInstallTime;
9934            ps.lastUpdateTime = lastUpdateTime;
9935        }
9936        // Set children install/update time
9937        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9938        for (int i = 0; i < childCount; i++) {
9939            PackageParser.Package childPkg = pkg.childPackages.get(i);
9940            ps = (PackageSetting) childPkg.mExtras;
9941            if (ps != null) {
9942                ps.firstInstallTime = firstInstallTime;
9943                ps.lastUpdateTime = lastUpdateTime;
9944            }
9945        }
9946    }
9947
9948    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
9949            PackageParser.Package changingLib) {
9950        if (file.path != null) {
9951            usesLibraryFiles.add(file.path);
9952            return;
9953        }
9954        PackageParser.Package p = mPackages.get(file.apk);
9955        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
9956            // If we are doing this while in the middle of updating a library apk,
9957            // then we need to make sure to use that new apk for determining the
9958            // dependencies here.  (We haven't yet finished committing the new apk
9959            // to the package manager state.)
9960            if (p == null || p.packageName.equals(changingLib.packageName)) {
9961                p = changingLib;
9962            }
9963        }
9964        if (p != null) {
9965            usesLibraryFiles.addAll(p.getAllCodePaths());
9966            if (p.usesLibraryFiles != null) {
9967                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
9968            }
9969        }
9970    }
9971
9972    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
9973            PackageParser.Package changingLib) throws PackageManagerException {
9974        if (pkg == null) {
9975            return;
9976        }
9977        ArraySet<String> usesLibraryFiles = null;
9978        if (pkg.usesLibraries != null) {
9979            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
9980                    null, null, pkg.packageName, changingLib, true, null);
9981        }
9982        if (pkg.usesStaticLibraries != null) {
9983            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
9984                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
9985                    pkg.packageName, changingLib, true, usesLibraryFiles);
9986        }
9987        if (pkg.usesOptionalLibraries != null) {
9988            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
9989                    null, null, pkg.packageName, changingLib, false, usesLibraryFiles);
9990        }
9991        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
9992            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
9993        } else {
9994            pkg.usesLibraryFiles = null;
9995        }
9996    }
9997
9998    private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
9999            @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests,
10000            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
10001            boolean required, @Nullable ArraySet<String> outUsedLibraries)
10002            throws PackageManagerException {
10003        final int libCount = requestedLibraries.size();
10004        for (int i = 0; i < libCount; i++) {
10005            final String libName = requestedLibraries.get(i);
10006            final int libVersion = requiredVersions != null ? requiredVersions[i]
10007                    : SharedLibraryInfo.VERSION_UNDEFINED;
10008            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
10009            if (libEntry == null) {
10010                if (required) {
10011                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10012                            "Package " + packageName + " requires unavailable shared library "
10013                                    + libName + "; failing!");
10014                } else if (DEBUG_SHARED_LIBRARIES) {
10015                    Slog.i(TAG, "Package " + packageName
10016                            + " desires unavailable shared library "
10017                            + libName + "; ignoring!");
10018                }
10019            } else {
10020                if (requiredVersions != null && requiredCertDigests != null) {
10021                    if (libEntry.info.getVersion() != requiredVersions[i]) {
10022                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10023                            "Package " + packageName + " requires unavailable static shared"
10024                                    + " library " + libName + " version "
10025                                    + libEntry.info.getVersion() + "; failing!");
10026                    }
10027
10028                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
10029                    if (libPkg == null) {
10030                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10031                                "Package " + packageName + " requires unavailable static shared"
10032                                        + " library; failing!");
10033                    }
10034
10035                    String expectedCertDigest = requiredCertDigests[i];
10036                    String libCertDigest = PackageUtils.computeCertSha256Digest(
10037                                libPkg.mSignatures[0]);
10038                    if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) {
10039                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10040                                "Package " + packageName + " requires differently signed" +
10041                                        " static shared library; failing!");
10042                    }
10043                }
10044
10045                if (outUsedLibraries == null) {
10046                    outUsedLibraries = new ArraySet<>();
10047                }
10048                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
10049            }
10050        }
10051        return outUsedLibraries;
10052    }
10053
10054    private static boolean hasString(List<String> list, List<String> which) {
10055        if (list == null) {
10056            return false;
10057        }
10058        for (int i=list.size()-1; i>=0; i--) {
10059            for (int j=which.size()-1; j>=0; j--) {
10060                if (which.get(j).equals(list.get(i))) {
10061                    return true;
10062                }
10063            }
10064        }
10065        return false;
10066    }
10067
10068    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
10069            PackageParser.Package changingPkg) {
10070        ArrayList<PackageParser.Package> res = null;
10071        for (PackageParser.Package pkg : mPackages.values()) {
10072            if (changingPkg != null
10073                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
10074                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
10075                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
10076                            changingPkg.staticSharedLibName)) {
10077                return null;
10078            }
10079            if (res == null) {
10080                res = new ArrayList<>();
10081            }
10082            res.add(pkg);
10083            try {
10084                updateSharedLibrariesLPr(pkg, changingPkg);
10085            } catch (PackageManagerException e) {
10086                // If a system app update or an app and a required lib missing we
10087                // delete the package and for updated system apps keep the data as
10088                // it is better for the user to reinstall than to be in an limbo
10089                // state. Also libs disappearing under an app should never happen
10090                // - just in case.
10091                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
10092                    final int flags = pkg.isUpdatedSystemApp()
10093                            ? PackageManager.DELETE_KEEP_DATA : 0;
10094                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
10095                            flags , null, true, null);
10096                }
10097                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
10098            }
10099        }
10100        return res;
10101    }
10102
10103    /**
10104     * Derive the value of the {@code cpuAbiOverride} based on the provided
10105     * value and an optional stored value from the package settings.
10106     */
10107    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
10108        String cpuAbiOverride = null;
10109
10110        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
10111            cpuAbiOverride = null;
10112        } else if (abiOverride != null) {
10113            cpuAbiOverride = abiOverride;
10114        } else if (settings != null) {
10115            cpuAbiOverride = settings.cpuAbiOverrideString;
10116        }
10117
10118        return cpuAbiOverride;
10119    }
10120
10121    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
10122            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
10123                    throws PackageManagerException {
10124        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
10125        // If the package has children and this is the first dive in the function
10126        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
10127        // whether all packages (parent and children) would be successfully scanned
10128        // before the actual scan since scanning mutates internal state and we want
10129        // to atomically install the package and its children.
10130        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10131            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
10132                scanFlags |= SCAN_CHECK_ONLY;
10133            }
10134        } else {
10135            scanFlags &= ~SCAN_CHECK_ONLY;
10136        }
10137
10138        final PackageParser.Package scannedPkg;
10139        try {
10140            // Scan the parent
10141            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
10142            // Scan the children
10143            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10144            for (int i = 0; i < childCount; i++) {
10145                PackageParser.Package childPkg = pkg.childPackages.get(i);
10146                scanPackageLI(childPkg, policyFlags,
10147                        scanFlags, currentTime, user);
10148            }
10149        } finally {
10150            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10151        }
10152
10153        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10154            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
10155        }
10156
10157        return scannedPkg;
10158    }
10159
10160    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
10161            int scanFlags, long currentTime, @Nullable UserHandle user)
10162                    throws PackageManagerException {
10163        boolean success = false;
10164        try {
10165            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
10166                    currentTime, user);
10167            success = true;
10168            return res;
10169        } finally {
10170            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
10171                // DELETE_DATA_ON_FAILURES is only used by frozen paths
10172                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
10173                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
10174                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
10175            }
10176        }
10177    }
10178
10179    /**
10180     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
10181     */
10182    private static boolean apkHasCode(String fileName) {
10183        StrictJarFile jarFile = null;
10184        try {
10185            jarFile = new StrictJarFile(fileName,
10186                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
10187            return jarFile.findEntry("classes.dex") != null;
10188        } catch (IOException ignore) {
10189        } finally {
10190            try {
10191                if (jarFile != null) {
10192                    jarFile.close();
10193                }
10194            } catch (IOException ignore) {}
10195        }
10196        return false;
10197    }
10198
10199    /**
10200     * Enforces code policy for the package. This ensures that if an APK has
10201     * declared hasCode="true" in its manifest that the APK actually contains
10202     * code.
10203     *
10204     * @throws PackageManagerException If bytecode could not be found when it should exist
10205     */
10206    private static void assertCodePolicy(PackageParser.Package pkg)
10207            throws PackageManagerException {
10208        final boolean shouldHaveCode =
10209                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10210        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10211            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10212                    "Package " + pkg.baseCodePath + " code is missing");
10213        }
10214
10215        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10216            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10217                final boolean splitShouldHaveCode =
10218                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10219                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10220                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10221                            "Package " + pkg.splitCodePaths[i] + " code is missing");
10222                }
10223            }
10224        }
10225    }
10226
10227    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
10228            final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
10229                    throws PackageManagerException {
10230        if (DEBUG_PACKAGE_SCANNING) {
10231            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10232                Log.d(TAG, "Scanning package " + pkg.packageName);
10233        }
10234
10235        applyPolicy(pkg, policyFlags);
10236
10237        assertPackageIsValid(pkg, policyFlags, scanFlags);
10238
10239        // Initialize package source and resource directories
10240        final File scanFile = new File(pkg.codePath);
10241        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10242        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10243
10244        SharedUserSetting suid = null;
10245        PackageSetting pkgSetting = null;
10246
10247        // Getting the package setting may have a side-effect, so if we
10248        // are only checking if scan would succeed, stash a copy of the
10249        // old setting to restore at the end.
10250        PackageSetting nonMutatedPs = null;
10251
10252        // We keep references to the derived CPU Abis from settings in oder to reuse
10253        // them in the case where we're not upgrading or booting for the first time.
10254        String primaryCpuAbiFromSettings = null;
10255        String secondaryCpuAbiFromSettings = null;
10256
10257        // writer
10258        synchronized (mPackages) {
10259            if (pkg.mSharedUserId != null) {
10260                // SIDE EFFECTS; may potentially allocate a new shared user
10261                suid = mSettings.getSharedUserLPw(
10262                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
10263                if (DEBUG_PACKAGE_SCANNING) {
10264                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10265                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
10266                                + "): packages=" + suid.packages);
10267                }
10268            }
10269
10270            // Check if we are renaming from an original package name.
10271            PackageSetting origPackage = null;
10272            String realName = null;
10273            if (pkg.mOriginalPackages != null) {
10274                // This package may need to be renamed to a previously
10275                // installed name.  Let's check on that...
10276                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
10277                if (pkg.mOriginalPackages.contains(renamed)) {
10278                    // This package had originally been installed as the
10279                    // original name, and we have already taken care of
10280                    // transitioning to the new one.  Just update the new
10281                    // one to continue using the old name.
10282                    realName = pkg.mRealPackage;
10283                    if (!pkg.packageName.equals(renamed)) {
10284                        // Callers into this function may have already taken
10285                        // care of renaming the package; only do it here if
10286                        // it is not already done.
10287                        pkg.setPackageName(renamed);
10288                    }
10289                } else {
10290                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
10291                        if ((origPackage = mSettings.getPackageLPr(
10292                                pkg.mOriginalPackages.get(i))) != null) {
10293                            // We do have the package already installed under its
10294                            // original name...  should we use it?
10295                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
10296                                // New package is not compatible with original.
10297                                origPackage = null;
10298                                continue;
10299                            } else if (origPackage.sharedUser != null) {
10300                                // Make sure uid is compatible between packages.
10301                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
10302                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
10303                                            + " to " + pkg.packageName + ": old uid "
10304                                            + origPackage.sharedUser.name
10305                                            + " differs from " + pkg.mSharedUserId);
10306                                    origPackage = null;
10307                                    continue;
10308                                }
10309                                // TODO: Add case when shared user id is added [b/28144775]
10310                            } else {
10311                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10312                                        + pkg.packageName + " to old name " + origPackage.name);
10313                            }
10314                            break;
10315                        }
10316                    }
10317                }
10318            }
10319
10320            if (mTransferedPackages.contains(pkg.packageName)) {
10321                Slog.w(TAG, "Package " + pkg.packageName
10322                        + " was transferred to another, but its .apk remains");
10323            }
10324
10325            // See comments in nonMutatedPs declaration
10326            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10327                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10328                if (foundPs != null) {
10329                    nonMutatedPs = new PackageSetting(foundPs);
10330                }
10331            }
10332
10333            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
10334                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10335                if (foundPs != null) {
10336                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
10337                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
10338                }
10339            }
10340
10341            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
10342            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
10343                PackageManagerService.reportSettingsProblem(Log.WARN,
10344                        "Package " + pkg.packageName + " shared user changed from "
10345                                + (pkgSetting.sharedUser != null
10346                                        ? pkgSetting.sharedUser.name : "<nothing>")
10347                                + " to "
10348                                + (suid != null ? suid.name : "<nothing>")
10349                                + "; replacing with new");
10350                pkgSetting = null;
10351            }
10352            final PackageSetting oldPkgSetting =
10353                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
10354            final PackageSetting disabledPkgSetting =
10355                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
10356
10357            String[] usesStaticLibraries = null;
10358            if (pkg.usesStaticLibraries != null) {
10359                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10360                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10361            }
10362
10363            if (pkgSetting == null) {
10364                final String parentPackageName = (pkg.parentPackage != null)
10365                        ? pkg.parentPackage.packageName : null;
10366                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10367                // REMOVE SharedUserSetting from method; update in a separate call
10368                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
10369                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
10370                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
10371                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
10372                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
10373                        true /*allowInstall*/, instantApp, parentPackageName,
10374                        pkg.getChildPackageNames(), UserManagerService.getInstance(),
10375                        usesStaticLibraries, pkg.usesStaticLibrariesVersions);
10376                // SIDE EFFECTS; updates system state; move elsewhere
10377                if (origPackage != null) {
10378                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
10379                }
10380                mSettings.addUserToSettingLPw(pkgSetting);
10381            } else {
10382                // REMOVE SharedUserSetting from method; update in a separate call.
10383                //
10384                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10385                // secondaryCpuAbi are not known at this point so we always update them
10386                // to null here, only to reset them at a later point.
10387                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
10388                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
10389                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
10390                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
10391                        UserManagerService.getInstance(), usesStaticLibraries,
10392                        pkg.usesStaticLibrariesVersions);
10393            }
10394            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
10395            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10396
10397            // SIDE EFFECTS; modifies system state; move elsewhere
10398            if (pkgSetting.origPackage != null) {
10399                // If we are first transitioning from an original package,
10400                // fix up the new package's name now.  We need to do this after
10401                // looking up the package under its new name, so getPackageLP
10402                // can take care of fiddling things correctly.
10403                pkg.setPackageName(origPackage.name);
10404
10405                // File a report about this.
10406                String msg = "New package " + pkgSetting.realName
10407                        + " renamed to replace old package " + pkgSetting.name;
10408                reportSettingsProblem(Log.WARN, msg);
10409
10410                // Make a note of it.
10411                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10412                    mTransferedPackages.add(origPackage.name);
10413                }
10414
10415                // No longer need to retain this.
10416                pkgSetting.origPackage = null;
10417            }
10418
10419            // SIDE EFFECTS; modifies system state; move elsewhere
10420            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
10421                // Make a note of it.
10422                mTransferedPackages.add(pkg.packageName);
10423            }
10424
10425            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
10426                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10427            }
10428
10429            if ((scanFlags & SCAN_BOOTING) == 0
10430                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10431                // Check all shared libraries and map to their actual file path.
10432                // We only do this here for apps not on a system dir, because those
10433                // are the only ones that can fail an install due to this.  We
10434                // will take care of the system apps by updating all of their
10435                // library paths after the scan is done. Also during the initial
10436                // scan don't update any libs as we do this wholesale after all
10437                // apps are scanned to avoid dependency based scanning.
10438                updateSharedLibrariesLPr(pkg, null);
10439            }
10440
10441            if (mFoundPolicyFile) {
10442                SELinuxMMAC.assignSeInfoValue(pkg);
10443            }
10444            pkg.applicationInfo.uid = pkgSetting.appId;
10445            pkg.mExtras = pkgSetting;
10446
10447
10448            // Static shared libs have same package with different versions where
10449            // we internally use a synthetic package name to allow multiple versions
10450            // of the same package, therefore we need to compare signatures against
10451            // the package setting for the latest library version.
10452            PackageSetting signatureCheckPs = pkgSetting;
10453            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10454                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10455                if (libraryEntry != null) {
10456                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10457                }
10458            }
10459
10460            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
10461                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
10462                    // We just determined the app is signed correctly, so bring
10463                    // over the latest parsed certs.
10464                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10465                } else {
10466                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10467                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10468                                "Package " + pkg.packageName + " upgrade keys do not match the "
10469                                + "previously installed version");
10470                    } else {
10471                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
10472                        String msg = "System package " + pkg.packageName
10473                                + " signature changed; retaining data.";
10474                        reportSettingsProblem(Log.WARN, msg);
10475                    }
10476                }
10477            } else {
10478                try {
10479                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
10480                    verifySignaturesLP(signatureCheckPs, pkg);
10481                    // We just determined the app is signed correctly, so bring
10482                    // over the latest parsed certs.
10483                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10484                } catch (PackageManagerException e) {
10485                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10486                        throw e;
10487                    }
10488                    // The signature has changed, but this package is in the system
10489                    // image...  let's recover!
10490                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10491                    // However...  if this package is part of a shared user, but it
10492                    // doesn't match the signature of the shared user, let's fail.
10493                    // What this means is that you can't change the signatures
10494                    // associated with an overall shared user, which doesn't seem all
10495                    // that unreasonable.
10496                    if (signatureCheckPs.sharedUser != null) {
10497                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
10498                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
10499                            throw new PackageManagerException(
10500                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10501                                    "Signature mismatch for shared user: "
10502                                            + pkgSetting.sharedUser);
10503                        }
10504                    }
10505                    // File a report about this.
10506                    String msg = "System package " + pkg.packageName
10507                            + " signature changed; retaining data.";
10508                    reportSettingsProblem(Log.WARN, msg);
10509                }
10510            }
10511
10512            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
10513                // This package wants to adopt ownership of permissions from
10514                // another package.
10515                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
10516                    final String origName = pkg.mAdoptPermissions.get(i);
10517                    final PackageSetting orig = mSettings.getPackageLPr(origName);
10518                    if (orig != null) {
10519                        if (verifyPackageUpdateLPr(orig, pkg)) {
10520                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
10521                                    + pkg.packageName);
10522                            // SIDE EFFECTS; updates permissions system state; move elsewhere
10523                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
10524                        }
10525                    }
10526                }
10527            }
10528        }
10529
10530        pkg.applicationInfo.processName = fixProcessName(
10531                pkg.applicationInfo.packageName,
10532                pkg.applicationInfo.processName);
10533
10534        if (pkg != mPlatformPackage) {
10535            // Get all of our default paths setup
10536            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10537        }
10538
10539        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10540
10541        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10542            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
10543                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10544                final boolean extractNativeLibs = !pkg.isLibrary();
10545                derivePackageAbi(pkg, scanFile, cpuAbiOverride, extractNativeLibs,
10546                        mAppLib32InstallDir);
10547                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10548
10549                // Some system apps still use directory structure for native libraries
10550                // in which case we might end up not detecting abi solely based on apk
10551                // structure. Try to detect abi based on directory structure.
10552                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
10553                        pkg.applicationInfo.primaryCpuAbi == null) {
10554                    setBundledAppAbisAndRoots(pkg, pkgSetting);
10555                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10556                }
10557            } else {
10558                // This is not a first boot or an upgrade, don't bother deriving the
10559                // ABI during the scan. Instead, trust the value that was stored in the
10560                // package setting.
10561                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
10562                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
10563
10564                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10565
10566                if (DEBUG_ABI_SELECTION) {
10567                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
10568                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
10569                        pkg.applicationInfo.secondaryCpuAbi);
10570                }
10571            }
10572        } else {
10573            if ((scanFlags & SCAN_MOVE) != 0) {
10574                // We haven't run dex-opt for this move (since we've moved the compiled output too)
10575                // but we already have this packages package info in the PackageSetting. We just
10576                // use that and derive the native library path based on the new codepath.
10577                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
10578                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
10579            }
10580
10581            // Set native library paths again. For moves, the path will be updated based on the
10582            // ABIs we've determined above. For non-moves, the path will be updated based on the
10583            // ABIs we determined during compilation, but the path will depend on the final
10584            // package path (after the rename away from the stage path).
10585            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10586        }
10587
10588        // This is a special case for the "system" package, where the ABI is
10589        // dictated by the zygote configuration (and init.rc). We should keep track
10590        // of this ABI so that we can deal with "normal" applications that run under
10591        // the same UID correctly.
10592        if (mPlatformPackage == pkg) {
10593            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
10594                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
10595        }
10596
10597        // If there's a mismatch between the abi-override in the package setting
10598        // and the abiOverride specified for the install. Warn about this because we
10599        // would've already compiled the app without taking the package setting into
10600        // account.
10601        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
10602            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
10603                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
10604                        " for package " + pkg.packageName);
10605            }
10606        }
10607
10608        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10609        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10610        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
10611
10612        // Copy the derived override back to the parsed package, so that we can
10613        // update the package settings accordingly.
10614        pkg.cpuAbiOverride = cpuAbiOverride;
10615
10616        if (DEBUG_ABI_SELECTION) {
10617            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
10618                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
10619                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
10620        }
10621
10622        // Push the derived path down into PackageSettings so we know what to
10623        // clean up at uninstall time.
10624        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
10625
10626        if (DEBUG_ABI_SELECTION) {
10627            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
10628                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
10629                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
10630        }
10631
10632        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
10633        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
10634            // We don't do this here during boot because we can do it all
10635            // at once after scanning all existing packages.
10636            //
10637            // We also do this *before* we perform dexopt on this package, so that
10638            // we can avoid redundant dexopts, and also to make sure we've got the
10639            // code and package path correct.
10640            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
10641        }
10642
10643        if (mFactoryTest && pkg.requestedPermissions.contains(
10644                android.Manifest.permission.FACTORY_TEST)) {
10645            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
10646        }
10647
10648        if (isSystemApp(pkg)) {
10649            pkgSetting.isOrphaned = true;
10650        }
10651
10652        // Take care of first install / last update times.
10653        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
10654        if (currentTime != 0) {
10655            if (pkgSetting.firstInstallTime == 0) {
10656                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
10657            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
10658                pkgSetting.lastUpdateTime = currentTime;
10659            }
10660        } else if (pkgSetting.firstInstallTime == 0) {
10661            // We need *something*.  Take time time stamp of the file.
10662            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
10663        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
10664            if (scanFileTime != pkgSetting.timeStamp) {
10665                // A package on the system image has changed; consider this
10666                // to be an update.
10667                pkgSetting.lastUpdateTime = scanFileTime;
10668            }
10669        }
10670        pkgSetting.setTimeStamp(scanFileTime);
10671
10672        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10673            if (nonMutatedPs != null) {
10674                synchronized (mPackages) {
10675                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
10676                }
10677            }
10678        } else {
10679            final int userId = user == null ? 0 : user.getIdentifier();
10680            // Modify state for the given package setting
10681            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
10682                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
10683            if (pkgSetting.getInstantApp(userId)) {
10684                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
10685            }
10686        }
10687        return pkg;
10688    }
10689
10690    /**
10691     * Applies policy to the parsed package based upon the given policy flags.
10692     * Ensures the package is in a good state.
10693     * <p>
10694     * Implementation detail: This method must NOT have any side effect. It would
10695     * ideally be static, but, it requires locks to read system state.
10696     */
10697    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
10698        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
10699            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
10700            if (pkg.applicationInfo.isDirectBootAware()) {
10701                // we're direct boot aware; set for all components
10702                for (PackageParser.Service s : pkg.services) {
10703                    s.info.encryptionAware = s.info.directBootAware = true;
10704                }
10705                for (PackageParser.Provider p : pkg.providers) {
10706                    p.info.encryptionAware = p.info.directBootAware = true;
10707                }
10708                for (PackageParser.Activity a : pkg.activities) {
10709                    a.info.encryptionAware = a.info.directBootAware = true;
10710                }
10711                for (PackageParser.Activity r : pkg.receivers) {
10712                    r.info.encryptionAware = r.info.directBootAware = true;
10713                }
10714            }
10715        } else {
10716            // Only allow system apps to be flagged as core apps.
10717            pkg.coreApp = false;
10718            // clear flags not applicable to regular apps
10719            pkg.applicationInfo.privateFlags &=
10720                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
10721            pkg.applicationInfo.privateFlags &=
10722                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
10723        }
10724        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
10725
10726        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
10727            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
10728        }
10729
10730        if (!isSystemApp(pkg)) {
10731            // Only system apps can use these features.
10732            pkg.mOriginalPackages = null;
10733            pkg.mRealPackage = null;
10734            pkg.mAdoptPermissions = null;
10735        }
10736    }
10737
10738    /**
10739     * Asserts the parsed package is valid according to the given policy. If the
10740     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
10741     * <p>
10742     * Implementation detail: This method must NOT have any side effects. It would
10743     * ideally be static, but, it requires locks to read system state.
10744     *
10745     * @throws PackageManagerException If the package fails any of the validation checks
10746     */
10747    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
10748            throws PackageManagerException {
10749        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
10750            assertCodePolicy(pkg);
10751        }
10752
10753        if (pkg.applicationInfo.getCodePath() == null ||
10754                pkg.applicationInfo.getResourcePath() == null) {
10755            // Bail out. The resource and code paths haven't been set.
10756            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10757                    "Code and resource paths haven't been set correctly");
10758        }
10759
10760        // Make sure we're not adding any bogus keyset info
10761        KeySetManagerService ksms = mSettings.mKeySetManagerService;
10762        ksms.assertScannedPackageValid(pkg);
10763
10764        synchronized (mPackages) {
10765            // The special "android" package can only be defined once
10766            if (pkg.packageName.equals("android")) {
10767                if (mAndroidApplication != null) {
10768                    Slog.w(TAG, "*************************************************");
10769                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
10770                    Slog.w(TAG, " codePath=" + pkg.codePath);
10771                    Slog.w(TAG, "*************************************************");
10772                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10773                            "Core android package being redefined.  Skipping.");
10774                }
10775            }
10776
10777            // A package name must be unique; don't allow duplicates
10778            if (mPackages.containsKey(pkg.packageName)) {
10779                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10780                        "Application package " + pkg.packageName
10781                        + " already installed.  Skipping duplicate.");
10782            }
10783
10784            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10785                // Static libs have a synthetic package name containing the version
10786                // but we still want the base name to be unique.
10787                if (mPackages.containsKey(pkg.manifestPackageName)) {
10788                    throw new PackageManagerException(
10789                            "Duplicate static shared lib provider package");
10790                }
10791
10792                // Static shared libraries should have at least O target SDK
10793                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
10794                    throw new PackageManagerException(
10795                            "Packages declaring static-shared libs must target O SDK or higher");
10796                }
10797
10798                // Package declaring static a shared lib cannot be instant apps
10799                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10800                    throw new PackageManagerException(
10801                            "Packages declaring static-shared libs cannot be instant apps");
10802                }
10803
10804                // Package declaring static a shared lib cannot be renamed since the package
10805                // name is synthetic and apps can't code around package manager internals.
10806                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
10807                    throw new PackageManagerException(
10808                            "Packages declaring static-shared libs cannot be renamed");
10809                }
10810
10811                // Package declaring static a shared lib cannot declare child packages
10812                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
10813                    throw new PackageManagerException(
10814                            "Packages declaring static-shared libs cannot have child packages");
10815                }
10816
10817                // Package declaring static a shared lib cannot declare dynamic libs
10818                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
10819                    throw new PackageManagerException(
10820                            "Packages declaring static-shared libs cannot declare dynamic libs");
10821                }
10822
10823                // Package declaring static a shared lib cannot declare shared users
10824                if (pkg.mSharedUserId != null) {
10825                    throw new PackageManagerException(
10826                            "Packages declaring static-shared libs cannot declare shared users");
10827                }
10828
10829                // Static shared libs cannot declare activities
10830                if (!pkg.activities.isEmpty()) {
10831                    throw new PackageManagerException(
10832                            "Static shared libs cannot declare activities");
10833                }
10834
10835                // Static shared libs cannot declare services
10836                if (!pkg.services.isEmpty()) {
10837                    throw new PackageManagerException(
10838                            "Static shared libs cannot declare services");
10839                }
10840
10841                // Static shared libs cannot declare providers
10842                if (!pkg.providers.isEmpty()) {
10843                    throw new PackageManagerException(
10844                            "Static shared libs cannot declare content providers");
10845                }
10846
10847                // Static shared libs cannot declare receivers
10848                if (!pkg.receivers.isEmpty()) {
10849                    throw new PackageManagerException(
10850                            "Static shared libs cannot declare broadcast receivers");
10851                }
10852
10853                // Static shared libs cannot declare permission groups
10854                if (!pkg.permissionGroups.isEmpty()) {
10855                    throw new PackageManagerException(
10856                            "Static shared libs cannot declare permission groups");
10857                }
10858
10859                // Static shared libs cannot declare permissions
10860                if (!pkg.permissions.isEmpty()) {
10861                    throw new PackageManagerException(
10862                            "Static shared libs cannot declare permissions");
10863                }
10864
10865                // Static shared libs cannot declare protected broadcasts
10866                if (pkg.protectedBroadcasts != null) {
10867                    throw new PackageManagerException(
10868                            "Static shared libs cannot declare protected broadcasts");
10869                }
10870
10871                // Static shared libs cannot be overlay targets
10872                if (pkg.mOverlayTarget != null) {
10873                    throw new PackageManagerException(
10874                            "Static shared libs cannot be overlay targets");
10875                }
10876
10877                // The version codes must be ordered as lib versions
10878                int minVersionCode = Integer.MIN_VALUE;
10879                int maxVersionCode = Integer.MAX_VALUE;
10880
10881                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10882                        pkg.staticSharedLibName);
10883                if (versionedLib != null) {
10884                    final int versionCount = versionedLib.size();
10885                    for (int i = 0; i < versionCount; i++) {
10886                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
10887                        final int libVersionCode = libInfo.getDeclaringPackage()
10888                                .getVersionCode();
10889                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
10890                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
10891                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
10892                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
10893                        } else {
10894                            minVersionCode = maxVersionCode = libVersionCode;
10895                            break;
10896                        }
10897                    }
10898                }
10899                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
10900                    throw new PackageManagerException("Static shared"
10901                            + " lib version codes must be ordered as lib versions");
10902                }
10903            }
10904
10905            // Only privileged apps and updated privileged apps can add child packages.
10906            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
10907                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
10908                    throw new PackageManagerException("Only privileged apps can add child "
10909                            + "packages. Ignoring package " + pkg.packageName);
10910                }
10911                final int childCount = pkg.childPackages.size();
10912                for (int i = 0; i < childCount; i++) {
10913                    PackageParser.Package childPkg = pkg.childPackages.get(i);
10914                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
10915                            childPkg.packageName)) {
10916                        throw new PackageManagerException("Can't override child of "
10917                                + "another disabled app. Ignoring package " + pkg.packageName);
10918                    }
10919                }
10920            }
10921
10922            // If we're only installing presumed-existing packages, require that the
10923            // scanned APK is both already known and at the path previously established
10924            // for it.  Previously unknown packages we pick up normally, but if we have an
10925            // a priori expectation about this package's install presence, enforce it.
10926            // With a singular exception for new system packages. When an OTA contains
10927            // a new system package, we allow the codepath to change from a system location
10928            // to the user-installed location. If we don't allow this change, any newer,
10929            // user-installed version of the application will be ignored.
10930            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
10931                if (mExpectingBetter.containsKey(pkg.packageName)) {
10932                    logCriticalInfo(Log.WARN,
10933                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
10934                } else {
10935                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
10936                    if (known != null) {
10937                        if (DEBUG_PACKAGE_SCANNING) {
10938                            Log.d(TAG, "Examining " + pkg.codePath
10939                                    + " and requiring known paths " + known.codePathString
10940                                    + " & " + known.resourcePathString);
10941                        }
10942                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
10943                                || !pkg.applicationInfo.getResourcePath().equals(
10944                                        known.resourcePathString)) {
10945                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
10946                                    "Application package " + pkg.packageName
10947                                    + " found at " + pkg.applicationInfo.getCodePath()
10948                                    + " but expected at " + known.codePathString
10949                                    + "; ignoring.");
10950                        }
10951                    }
10952                }
10953            }
10954
10955            // Verify that this new package doesn't have any content providers
10956            // that conflict with existing packages.  Only do this if the
10957            // package isn't already installed, since we don't want to break
10958            // things that are installed.
10959            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
10960                final int N = pkg.providers.size();
10961                int i;
10962                for (i=0; i<N; i++) {
10963                    PackageParser.Provider p = pkg.providers.get(i);
10964                    if (p.info.authority != null) {
10965                        String names[] = p.info.authority.split(";");
10966                        for (int j = 0; j < names.length; j++) {
10967                            if (mProvidersByAuthority.containsKey(names[j])) {
10968                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10969                                final String otherPackageName =
10970                                        ((other != null && other.getComponentName() != null) ?
10971                                                other.getComponentName().getPackageName() : "?");
10972                                throw new PackageManagerException(
10973                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
10974                                        "Can't install because provider name " + names[j]
10975                                                + " (in package " + pkg.applicationInfo.packageName
10976                                                + ") is already used by " + otherPackageName);
10977                            }
10978                        }
10979                    }
10980                }
10981            }
10982        }
10983    }
10984
10985    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
10986            int type, String declaringPackageName, int declaringVersionCode) {
10987        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10988        if (versionedLib == null) {
10989            versionedLib = new SparseArray<>();
10990            mSharedLibraries.put(name, versionedLib);
10991            if (type == SharedLibraryInfo.TYPE_STATIC) {
10992                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
10993            }
10994        } else if (versionedLib.indexOfKey(version) >= 0) {
10995            return false;
10996        }
10997        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
10998                version, type, declaringPackageName, declaringVersionCode);
10999        versionedLib.put(version, libEntry);
11000        return true;
11001    }
11002
11003    private boolean removeSharedLibraryLPw(String name, int version) {
11004        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11005        if (versionedLib == null) {
11006            return false;
11007        }
11008        final int libIdx = versionedLib.indexOfKey(version);
11009        if (libIdx < 0) {
11010            return false;
11011        }
11012        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
11013        versionedLib.remove(version);
11014        if (versionedLib.size() <= 0) {
11015            mSharedLibraries.remove(name);
11016            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
11017                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
11018                        .getPackageName());
11019            }
11020        }
11021        return true;
11022    }
11023
11024    /**
11025     * Adds a scanned package to the system. When this method is finished, the package will
11026     * be available for query, resolution, etc...
11027     */
11028    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
11029            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
11030        final String pkgName = pkg.packageName;
11031        if (mCustomResolverComponentName != null &&
11032                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
11033            setUpCustomResolverActivity(pkg);
11034        }
11035
11036        if (pkg.packageName.equals("android")) {
11037            synchronized (mPackages) {
11038                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
11039                    // Set up information for our fall-back user intent resolution activity.
11040                    mPlatformPackage = pkg;
11041                    pkg.mVersionCode = mSdkVersion;
11042                    mAndroidApplication = pkg.applicationInfo;
11043                    if (!mResolverReplaced) {
11044                        mResolveActivity.applicationInfo = mAndroidApplication;
11045                        mResolveActivity.name = ResolverActivity.class.getName();
11046                        mResolveActivity.packageName = mAndroidApplication.packageName;
11047                        mResolveActivity.processName = "system:ui";
11048                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11049                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
11050                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
11051                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
11052                        mResolveActivity.exported = true;
11053                        mResolveActivity.enabled = true;
11054                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
11055                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
11056                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
11057                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
11058                                | ActivityInfo.CONFIG_ORIENTATION
11059                                | ActivityInfo.CONFIG_KEYBOARD
11060                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
11061                        mResolveInfo.activityInfo = mResolveActivity;
11062                        mResolveInfo.priority = 0;
11063                        mResolveInfo.preferredOrder = 0;
11064                        mResolveInfo.match = 0;
11065                        mResolveComponentName = new ComponentName(
11066                                mAndroidApplication.packageName, mResolveActivity.name);
11067                    }
11068                }
11069            }
11070        }
11071
11072        ArrayList<PackageParser.Package> clientLibPkgs = null;
11073        // writer
11074        synchronized (mPackages) {
11075            boolean hasStaticSharedLibs = false;
11076
11077            // Any app can add new static shared libraries
11078            if (pkg.staticSharedLibName != null) {
11079                // Static shared libs don't allow renaming as they have synthetic package
11080                // names to allow install of multiple versions, so use name from manifest.
11081                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
11082                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
11083                        pkg.manifestPackageName, pkg.mVersionCode)) {
11084                    hasStaticSharedLibs = true;
11085                } else {
11086                    Slog.w(TAG, "Package " + pkg.packageName + " library "
11087                                + pkg.staticSharedLibName + " already exists; skipping");
11088                }
11089                // Static shared libs cannot be updated once installed since they
11090                // use synthetic package name which includes the version code, so
11091                // not need to update other packages's shared lib dependencies.
11092            }
11093
11094            if (!hasStaticSharedLibs
11095                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11096                // Only system apps can add new dynamic shared libraries.
11097                if (pkg.libraryNames != null) {
11098                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
11099                        String name = pkg.libraryNames.get(i);
11100                        boolean allowed = false;
11101                        if (pkg.isUpdatedSystemApp()) {
11102                            // New library entries can only be added through the
11103                            // system image.  This is important to get rid of a lot
11104                            // of nasty edge cases: for example if we allowed a non-
11105                            // system update of the app to add a library, then uninstalling
11106                            // the update would make the library go away, and assumptions
11107                            // we made such as through app install filtering would now
11108                            // have allowed apps on the device which aren't compatible
11109                            // with it.  Better to just have the restriction here, be
11110                            // conservative, and create many fewer cases that can negatively
11111                            // impact the user experience.
11112                            final PackageSetting sysPs = mSettings
11113                                    .getDisabledSystemPkgLPr(pkg.packageName);
11114                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
11115                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
11116                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
11117                                        allowed = true;
11118                                        break;
11119                                    }
11120                                }
11121                            }
11122                        } else {
11123                            allowed = true;
11124                        }
11125                        if (allowed) {
11126                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
11127                                    SharedLibraryInfo.VERSION_UNDEFINED,
11128                                    SharedLibraryInfo.TYPE_DYNAMIC,
11129                                    pkg.packageName, pkg.mVersionCode)) {
11130                                Slog.w(TAG, "Package " + pkg.packageName + " library "
11131                                        + name + " already exists; skipping");
11132                            }
11133                        } else {
11134                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
11135                                    + name + " that is not declared on system image; skipping");
11136                        }
11137                    }
11138
11139                    if ((scanFlags & SCAN_BOOTING) == 0) {
11140                        // If we are not booting, we need to update any applications
11141                        // that are clients of our shared library.  If we are booting,
11142                        // this will all be done once the scan is complete.
11143                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
11144                    }
11145                }
11146            }
11147        }
11148
11149        if ((scanFlags & SCAN_BOOTING) != 0) {
11150            // No apps can run during boot scan, so they don't need to be frozen
11151        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
11152            // Caller asked to not kill app, so it's probably not frozen
11153        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
11154            // Caller asked us to ignore frozen check for some reason; they
11155            // probably didn't know the package name
11156        } else {
11157            // We're doing major surgery on this package, so it better be frozen
11158            // right now to keep it from launching
11159            checkPackageFrozen(pkgName);
11160        }
11161
11162        // Also need to kill any apps that are dependent on the library.
11163        if (clientLibPkgs != null) {
11164            for (int i=0; i<clientLibPkgs.size(); i++) {
11165                PackageParser.Package clientPkg = clientLibPkgs.get(i);
11166                killApplication(clientPkg.applicationInfo.packageName,
11167                        clientPkg.applicationInfo.uid, "update lib");
11168            }
11169        }
11170
11171        // writer
11172        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
11173
11174        synchronized (mPackages) {
11175            // We don't expect installation to fail beyond this point
11176
11177            // Add the new setting to mSettings
11178            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
11179            // Add the new setting to mPackages
11180            mPackages.put(pkg.applicationInfo.packageName, pkg);
11181            // Make sure we don't accidentally delete its data.
11182            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
11183            while (iter.hasNext()) {
11184                PackageCleanItem item = iter.next();
11185                if (pkgName.equals(item.packageName)) {
11186                    iter.remove();
11187                }
11188            }
11189
11190            // Add the package's KeySets to the global KeySetManagerService
11191            KeySetManagerService ksms = mSettings.mKeySetManagerService;
11192            ksms.addScannedPackageLPw(pkg);
11193
11194            int N = pkg.providers.size();
11195            StringBuilder r = null;
11196            int i;
11197            for (i=0; i<N; i++) {
11198                PackageParser.Provider p = pkg.providers.get(i);
11199                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11200                        p.info.processName);
11201                mProviders.addProvider(p);
11202                p.syncable = p.info.isSyncable;
11203                if (p.info.authority != null) {
11204                    String names[] = p.info.authority.split(";");
11205                    p.info.authority = null;
11206                    for (int j = 0; j < names.length; j++) {
11207                        if (j == 1 && p.syncable) {
11208                            // We only want the first authority for a provider to possibly be
11209                            // syncable, so if we already added this provider using a different
11210                            // authority clear the syncable flag. We copy the provider before
11211                            // changing it because the mProviders object contains a reference
11212                            // to a provider that we don't want to change.
11213                            // Only do this for the second authority since the resulting provider
11214                            // object can be the same for all future authorities for this provider.
11215                            p = new PackageParser.Provider(p);
11216                            p.syncable = false;
11217                        }
11218                        if (!mProvidersByAuthority.containsKey(names[j])) {
11219                            mProvidersByAuthority.put(names[j], p);
11220                            if (p.info.authority == null) {
11221                                p.info.authority = names[j];
11222                            } else {
11223                                p.info.authority = p.info.authority + ";" + names[j];
11224                            }
11225                            if (DEBUG_PACKAGE_SCANNING) {
11226                                if (chatty)
11227                                    Log.d(TAG, "Registered content provider: " + names[j]
11228                                            + ", className = " + p.info.name + ", isSyncable = "
11229                                            + p.info.isSyncable);
11230                            }
11231                        } else {
11232                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11233                            Slog.w(TAG, "Skipping provider name " + names[j] +
11234                                    " (in package " + pkg.applicationInfo.packageName +
11235                                    "): name already used by "
11236                                    + ((other != null && other.getComponentName() != null)
11237                                            ? other.getComponentName().getPackageName() : "?"));
11238                        }
11239                    }
11240                }
11241                if (chatty) {
11242                    if (r == null) {
11243                        r = new StringBuilder(256);
11244                    } else {
11245                        r.append(' ');
11246                    }
11247                    r.append(p.info.name);
11248                }
11249            }
11250            if (r != null) {
11251                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
11252            }
11253
11254            N = pkg.services.size();
11255            r = null;
11256            for (i=0; i<N; i++) {
11257                PackageParser.Service s = pkg.services.get(i);
11258                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11259                        s.info.processName);
11260                mServices.addService(s);
11261                if (chatty) {
11262                    if (r == null) {
11263                        r = new StringBuilder(256);
11264                    } else {
11265                        r.append(' ');
11266                    }
11267                    r.append(s.info.name);
11268                }
11269            }
11270            if (r != null) {
11271                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
11272            }
11273
11274            N = pkg.receivers.size();
11275            r = null;
11276            for (i=0; i<N; i++) {
11277                PackageParser.Activity a = pkg.receivers.get(i);
11278                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11279                        a.info.processName);
11280                mReceivers.addActivity(a, "receiver");
11281                if (chatty) {
11282                    if (r == null) {
11283                        r = new StringBuilder(256);
11284                    } else {
11285                        r.append(' ');
11286                    }
11287                    r.append(a.info.name);
11288                }
11289            }
11290            if (r != null) {
11291                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11292            }
11293
11294            N = pkg.activities.size();
11295            r = null;
11296            for (i=0; i<N; i++) {
11297                PackageParser.Activity a = pkg.activities.get(i);
11298                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11299                        a.info.processName);
11300                mActivities.addActivity(a, "activity");
11301                if (chatty) {
11302                    if (r == null) {
11303                        r = new StringBuilder(256);
11304                    } else {
11305                        r.append(' ');
11306                    }
11307                    r.append(a.info.name);
11308                }
11309            }
11310            if (r != null) {
11311                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11312            }
11313
11314            N = pkg.permissionGroups.size();
11315            r = null;
11316            for (i=0; i<N; i++) {
11317                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
11318                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
11319                final String curPackageName = cur == null ? null : cur.info.packageName;
11320                // Dont allow ephemeral apps to define new permission groups.
11321                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11322                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11323                            + pg.info.packageName
11324                            + " ignored: instant apps cannot define new permission groups.");
11325                    continue;
11326                }
11327                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
11328                if (cur == null || isPackageUpdate) {
11329                    mPermissionGroups.put(pg.info.name, pg);
11330                    if (chatty) {
11331                        if (r == null) {
11332                            r = new StringBuilder(256);
11333                        } else {
11334                            r.append(' ');
11335                        }
11336                        if (isPackageUpdate) {
11337                            r.append("UPD:");
11338                        }
11339                        r.append(pg.info.name);
11340                    }
11341                } else {
11342                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11343                            + pg.info.packageName + " ignored: original from "
11344                            + cur.info.packageName);
11345                    if (chatty) {
11346                        if (r == null) {
11347                            r = new StringBuilder(256);
11348                        } else {
11349                            r.append(' ');
11350                        }
11351                        r.append("DUP:");
11352                        r.append(pg.info.name);
11353                    }
11354                }
11355            }
11356            if (r != null) {
11357                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
11358            }
11359
11360            N = pkg.permissions.size();
11361            r = null;
11362            for (i=0; i<N; i++) {
11363                PackageParser.Permission p = pkg.permissions.get(i);
11364
11365                // Dont allow ephemeral apps to define new permissions.
11366                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11367                    Slog.w(TAG, "Permission " + p.info.name + " from package "
11368                            + p.info.packageName
11369                            + " ignored: instant apps cannot define new permissions.");
11370                    continue;
11371                }
11372
11373                // Assume by default that we did not install this permission into the system.
11374                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
11375
11376                // Now that permission groups have a special meaning, we ignore permission
11377                // groups for legacy apps to prevent unexpected behavior. In particular,
11378                // permissions for one app being granted to someone just because they happen
11379                // to be in a group defined by another app (before this had no implications).
11380                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
11381                    p.group = mPermissionGroups.get(p.info.group);
11382                    // Warn for a permission in an unknown group.
11383                    if (DEBUG_PERMISSIONS && p.info.group != null && p.group == null) {
11384                        Slog.i(TAG, "Permission " + p.info.name + " from package "
11385                                + p.info.packageName + " in an unknown group " + p.info.group);
11386                    }
11387                }
11388
11389                ArrayMap<String, BasePermission> permissionMap =
11390                        p.tree ? mSettings.mPermissionTrees
11391                                : mSettings.mPermissions;
11392                BasePermission bp = permissionMap.get(p.info.name);
11393
11394                // Allow system apps to redefine non-system permissions
11395                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
11396                    final boolean currentOwnerIsSystem = (bp.perm != null
11397                            && isSystemApp(bp.perm.owner));
11398                    if (isSystemApp(p.owner)) {
11399                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
11400                            // It's a built-in permission and no owner, take ownership now
11401                            bp.packageSetting = pkgSetting;
11402                            bp.perm = p;
11403                            bp.uid = pkg.applicationInfo.uid;
11404                            bp.sourcePackage = p.info.packageName;
11405                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11406                        } else if (!currentOwnerIsSystem) {
11407                            String msg = "New decl " + p.owner + " of permission  "
11408                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
11409                            reportSettingsProblem(Log.WARN, msg);
11410                            bp = null;
11411                        }
11412                    }
11413                }
11414
11415                if (bp == null) {
11416                    bp = new BasePermission(p.info.name, p.info.packageName,
11417                            BasePermission.TYPE_NORMAL);
11418                    permissionMap.put(p.info.name, bp);
11419                }
11420
11421                if (bp.perm == null) {
11422                    if (bp.sourcePackage == null
11423                            || bp.sourcePackage.equals(p.info.packageName)) {
11424                        BasePermission tree = findPermissionTreeLP(p.info.name);
11425                        if (tree == null
11426                                || tree.sourcePackage.equals(p.info.packageName)) {
11427                            bp.packageSetting = pkgSetting;
11428                            bp.perm = p;
11429                            bp.uid = pkg.applicationInfo.uid;
11430                            bp.sourcePackage = p.info.packageName;
11431                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11432                            if (chatty) {
11433                                if (r == null) {
11434                                    r = new StringBuilder(256);
11435                                } else {
11436                                    r.append(' ');
11437                                }
11438                                r.append(p.info.name);
11439                            }
11440                        } else {
11441                            Slog.w(TAG, "Permission " + p.info.name + " from package "
11442                                    + p.info.packageName + " ignored: base tree "
11443                                    + tree.name + " is from package "
11444                                    + tree.sourcePackage);
11445                        }
11446                    } else {
11447                        Slog.w(TAG, "Permission " + p.info.name + " from package "
11448                                + p.info.packageName + " ignored: original from "
11449                                + bp.sourcePackage);
11450                    }
11451                } else if (chatty) {
11452                    if (r == null) {
11453                        r = new StringBuilder(256);
11454                    } else {
11455                        r.append(' ');
11456                    }
11457                    r.append("DUP:");
11458                    r.append(p.info.name);
11459                }
11460                if (bp.perm == p) {
11461                    bp.protectionLevel = p.info.protectionLevel;
11462                }
11463            }
11464
11465            if (r != null) {
11466                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
11467            }
11468
11469            N = pkg.instrumentation.size();
11470            r = null;
11471            for (i=0; i<N; i++) {
11472                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11473                a.info.packageName = pkg.applicationInfo.packageName;
11474                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11475                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11476                a.info.splitNames = pkg.splitNames;
11477                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11478                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11479                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11480                a.info.dataDir = pkg.applicationInfo.dataDir;
11481                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11482                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11483                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11484                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11485                mInstrumentation.put(a.getComponentName(), a);
11486                if (chatty) {
11487                    if (r == null) {
11488                        r = new StringBuilder(256);
11489                    } else {
11490                        r.append(' ');
11491                    }
11492                    r.append(a.info.name);
11493                }
11494            }
11495            if (r != null) {
11496                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
11497            }
11498
11499            if (pkg.protectedBroadcasts != null) {
11500                N = pkg.protectedBroadcasts.size();
11501                synchronized (mProtectedBroadcasts) {
11502                    for (i = 0; i < N; i++) {
11503                        mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11504                    }
11505                }
11506            }
11507        }
11508
11509        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11510    }
11511
11512    /**
11513     * Derive the ABI of a non-system package located at {@code scanFile}. This information
11514     * is derived purely on the basis of the contents of {@code scanFile} and
11515     * {@code cpuAbiOverride}.
11516     *
11517     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
11518     */
11519    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
11520                                 String cpuAbiOverride, boolean extractLibs,
11521                                 File appLib32InstallDir)
11522            throws PackageManagerException {
11523        // Give ourselves some initial paths; we'll come back for another
11524        // pass once we've determined ABI below.
11525        setNativeLibraryPaths(pkg, appLib32InstallDir);
11526
11527        // We would never need to extract libs for forward-locked and external packages,
11528        // since the container service will do it for us. We shouldn't attempt to
11529        // extract libs from system app when it was not updated.
11530        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
11531                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
11532            extractLibs = false;
11533        }
11534
11535        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
11536        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
11537
11538        NativeLibraryHelper.Handle handle = null;
11539        try {
11540            handle = NativeLibraryHelper.Handle.create(pkg);
11541            // TODO(multiArch): This can be null for apps that didn't go through the
11542            // usual installation process. We can calculate it again, like we
11543            // do during install time.
11544            //
11545            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
11546            // unnecessary.
11547            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
11548
11549            // Null out the abis so that they can be recalculated.
11550            pkg.applicationInfo.primaryCpuAbi = null;
11551            pkg.applicationInfo.secondaryCpuAbi = null;
11552            if (isMultiArch(pkg.applicationInfo)) {
11553                // Warn if we've set an abiOverride for multi-lib packages..
11554                // By definition, we need to copy both 32 and 64 bit libraries for
11555                // such packages.
11556                if (pkg.cpuAbiOverride != null
11557                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
11558                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
11559                }
11560
11561                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
11562                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
11563                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
11564                    if (extractLibs) {
11565                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11566                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11567                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
11568                                useIsaSpecificSubdirs);
11569                    } else {
11570                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11571                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
11572                    }
11573                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11574                }
11575
11576                // Shared library native code should be in the APK zip aligned
11577                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
11578                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11579                            "Shared library native lib extraction not supported");
11580                }
11581
11582                maybeThrowExceptionForMultiArchCopy(
11583                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
11584
11585                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
11586                    if (extractLibs) {
11587                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11588                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11589                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
11590                                useIsaSpecificSubdirs);
11591                    } else {
11592                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11593                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
11594                    }
11595                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11596                }
11597
11598                maybeThrowExceptionForMultiArchCopy(
11599                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
11600
11601                if (abi64 >= 0) {
11602                    // Shared library native libs should be in the APK zip aligned
11603                    if (extractLibs && pkg.isLibrary()) {
11604                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11605                                "Shared library native lib extraction not supported");
11606                    }
11607                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
11608                }
11609
11610                if (abi32 >= 0) {
11611                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
11612                    if (abi64 >= 0) {
11613                        if (pkg.use32bitAbi) {
11614                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11615                            pkg.applicationInfo.primaryCpuAbi = abi;
11616                        } else {
11617                            pkg.applicationInfo.secondaryCpuAbi = abi;
11618                        }
11619                    } else {
11620                        pkg.applicationInfo.primaryCpuAbi = abi;
11621                    }
11622                }
11623            } else {
11624                String[] abiList = (cpuAbiOverride != null) ?
11625                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
11626
11627                // Enable gross and lame hacks for apps that are built with old
11628                // SDK tools. We must scan their APKs for renderscript bitcode and
11629                // not launch them if it's present. Don't bother checking on devices
11630                // that don't have 64 bit support.
11631                boolean needsRenderScriptOverride = false;
11632                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
11633                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
11634                    abiList = Build.SUPPORTED_32_BIT_ABIS;
11635                    needsRenderScriptOverride = true;
11636                }
11637
11638                final int copyRet;
11639                if (extractLibs) {
11640                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11641                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11642                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
11643                } else {
11644                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11645                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
11646                }
11647                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11648
11649                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
11650                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11651                            "Error unpackaging native libs for app, errorCode=" + copyRet);
11652                }
11653
11654                if (copyRet >= 0) {
11655                    // Shared libraries that have native libs must be multi-architecture
11656                    if (pkg.isLibrary()) {
11657                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11658                                "Shared library with native libs must be multiarch");
11659                    }
11660                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
11661                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
11662                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
11663                } else if (needsRenderScriptOverride) {
11664                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
11665                }
11666            }
11667        } catch (IOException ioe) {
11668            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
11669        } finally {
11670            IoUtils.closeQuietly(handle);
11671        }
11672
11673        // Now that we've calculated the ABIs and determined if it's an internal app,
11674        // we will go ahead and populate the nativeLibraryPath.
11675        setNativeLibraryPaths(pkg, appLib32InstallDir);
11676    }
11677
11678    /**
11679     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
11680     * i.e, so that all packages can be run inside a single process if required.
11681     *
11682     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
11683     * this function will either try and make the ABI for all packages in {@code packagesForUser}
11684     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
11685     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
11686     * updating a package that belongs to a shared user.
11687     *
11688     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
11689     * adds unnecessary complexity.
11690     */
11691    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
11692            PackageParser.Package scannedPackage) {
11693        String requiredInstructionSet = null;
11694        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
11695            requiredInstructionSet = VMRuntime.getInstructionSet(
11696                     scannedPackage.applicationInfo.primaryCpuAbi);
11697        }
11698
11699        PackageSetting requirer = null;
11700        for (PackageSetting ps : packagesForUser) {
11701            // If packagesForUser contains scannedPackage, we skip it. This will happen
11702            // when scannedPackage is an update of an existing package. Without this check,
11703            // we will never be able to change the ABI of any package belonging to a shared
11704            // user, even if it's compatible with other packages.
11705            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11706                if (ps.primaryCpuAbiString == null) {
11707                    continue;
11708                }
11709
11710                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
11711                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
11712                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
11713                    // this but there's not much we can do.
11714                    String errorMessage = "Instruction set mismatch, "
11715                            + ((requirer == null) ? "[caller]" : requirer)
11716                            + " requires " + requiredInstructionSet + " whereas " + ps
11717                            + " requires " + instructionSet;
11718                    Slog.w(TAG, errorMessage);
11719                }
11720
11721                if (requiredInstructionSet == null) {
11722                    requiredInstructionSet = instructionSet;
11723                    requirer = ps;
11724                }
11725            }
11726        }
11727
11728        if (requiredInstructionSet != null) {
11729            String adjustedAbi;
11730            if (requirer != null) {
11731                // requirer != null implies that either scannedPackage was null or that scannedPackage
11732                // did not require an ABI, in which case we have to adjust scannedPackage to match
11733                // the ABI of the set (which is the same as requirer's ABI)
11734                adjustedAbi = requirer.primaryCpuAbiString;
11735                if (scannedPackage != null) {
11736                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
11737                }
11738            } else {
11739                // requirer == null implies that we're updating all ABIs in the set to
11740                // match scannedPackage.
11741                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
11742            }
11743
11744            for (PackageSetting ps : packagesForUser) {
11745                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11746                    if (ps.primaryCpuAbiString != null) {
11747                        continue;
11748                    }
11749
11750                    ps.primaryCpuAbiString = adjustedAbi;
11751                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
11752                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
11753                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
11754                        if (DEBUG_ABI_SELECTION) {
11755                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
11756                                    + " (requirer="
11757                                    + (requirer != null ? requirer.pkg : "null")
11758                                    + ", scannedPackage="
11759                                    + (scannedPackage != null ? scannedPackage : "null")
11760                                    + ")");
11761                        }
11762                        try {
11763                            mInstaller.rmdex(ps.codePathString,
11764                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
11765                        } catch (InstallerException ignored) {
11766                        }
11767                    }
11768                }
11769            }
11770        }
11771    }
11772
11773    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
11774        synchronized (mPackages) {
11775            mResolverReplaced = true;
11776            // Set up information for custom user intent resolution activity.
11777            mResolveActivity.applicationInfo = pkg.applicationInfo;
11778            mResolveActivity.name = mCustomResolverComponentName.getClassName();
11779            mResolveActivity.packageName = pkg.applicationInfo.packageName;
11780            mResolveActivity.processName = pkg.applicationInfo.packageName;
11781            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11782            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
11783                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11784            mResolveActivity.theme = 0;
11785            mResolveActivity.exported = true;
11786            mResolveActivity.enabled = true;
11787            mResolveInfo.activityInfo = mResolveActivity;
11788            mResolveInfo.priority = 0;
11789            mResolveInfo.preferredOrder = 0;
11790            mResolveInfo.match = 0;
11791            mResolveComponentName = mCustomResolverComponentName;
11792            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
11793                    mResolveComponentName);
11794        }
11795    }
11796
11797    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
11798        if (installerActivity == null) {
11799            if (DEBUG_EPHEMERAL) {
11800                Slog.d(TAG, "Clear ephemeral installer activity");
11801            }
11802            mInstantAppInstallerActivity = null;
11803            return;
11804        }
11805
11806        if (DEBUG_EPHEMERAL) {
11807            Slog.d(TAG, "Set ephemeral installer activity: "
11808                    + installerActivity.getComponentName());
11809        }
11810        // Set up information for ephemeral installer activity
11811        mInstantAppInstallerActivity = installerActivity;
11812        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
11813                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11814        mInstantAppInstallerActivity.exported = true;
11815        mInstantAppInstallerActivity.enabled = true;
11816        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
11817        mInstantAppInstallerInfo.priority = 0;
11818        mInstantAppInstallerInfo.preferredOrder = 1;
11819        mInstantAppInstallerInfo.isDefault = true;
11820        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
11821                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
11822    }
11823
11824    private static String calculateBundledApkRoot(final String codePathString) {
11825        final File codePath = new File(codePathString);
11826        final File codeRoot;
11827        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
11828            codeRoot = Environment.getRootDirectory();
11829        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
11830            codeRoot = Environment.getOemDirectory();
11831        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
11832            codeRoot = Environment.getVendorDirectory();
11833        } else {
11834            // Unrecognized code path; take its top real segment as the apk root:
11835            // e.g. /something/app/blah.apk => /something
11836            try {
11837                File f = codePath.getCanonicalFile();
11838                File parent = f.getParentFile();    // non-null because codePath is a file
11839                File tmp;
11840                while ((tmp = parent.getParentFile()) != null) {
11841                    f = parent;
11842                    parent = tmp;
11843                }
11844                codeRoot = f;
11845                Slog.w(TAG, "Unrecognized code path "
11846                        + codePath + " - using " + codeRoot);
11847            } catch (IOException e) {
11848                // Can't canonicalize the code path -- shenanigans?
11849                Slog.w(TAG, "Can't canonicalize code path " + codePath);
11850                return Environment.getRootDirectory().getPath();
11851            }
11852        }
11853        return codeRoot.getPath();
11854    }
11855
11856    /**
11857     * Derive and set the location of native libraries for the given package,
11858     * which varies depending on where and how the package was installed.
11859     */
11860    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
11861        final ApplicationInfo info = pkg.applicationInfo;
11862        final String codePath = pkg.codePath;
11863        final File codeFile = new File(codePath);
11864        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
11865        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
11866
11867        info.nativeLibraryRootDir = null;
11868        info.nativeLibraryRootRequiresIsa = false;
11869        info.nativeLibraryDir = null;
11870        info.secondaryNativeLibraryDir = null;
11871
11872        if (isApkFile(codeFile)) {
11873            // Monolithic install
11874            if (bundledApp) {
11875                // If "/system/lib64/apkname" exists, assume that is the per-package
11876                // native library directory to use; otherwise use "/system/lib/apkname".
11877                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
11878                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
11879                        getPrimaryInstructionSet(info));
11880
11881                // This is a bundled system app so choose the path based on the ABI.
11882                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
11883                // is just the default path.
11884                final String apkName = deriveCodePathName(codePath);
11885                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
11886                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
11887                        apkName).getAbsolutePath();
11888
11889                if (info.secondaryCpuAbi != null) {
11890                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
11891                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
11892                            secondaryLibDir, apkName).getAbsolutePath();
11893                }
11894            } else if (asecApp) {
11895                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
11896                        .getAbsolutePath();
11897            } else {
11898                final String apkName = deriveCodePathName(codePath);
11899                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
11900                        .getAbsolutePath();
11901            }
11902
11903            info.nativeLibraryRootRequiresIsa = false;
11904            info.nativeLibraryDir = info.nativeLibraryRootDir;
11905        } else {
11906            // Cluster install
11907            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
11908            info.nativeLibraryRootRequiresIsa = true;
11909
11910            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
11911                    getPrimaryInstructionSet(info)).getAbsolutePath();
11912
11913            if (info.secondaryCpuAbi != null) {
11914                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
11915                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
11916            }
11917        }
11918    }
11919
11920    /**
11921     * Calculate the abis and roots for a bundled app. These can uniquely
11922     * be determined from the contents of the system partition, i.e whether
11923     * it contains 64 or 32 bit shared libraries etc. We do not validate any
11924     * of this information, and instead assume that the system was built
11925     * sensibly.
11926     */
11927    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
11928                                           PackageSetting pkgSetting) {
11929        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
11930
11931        // If "/system/lib64/apkname" exists, assume that is the per-package
11932        // native library directory to use; otherwise use "/system/lib/apkname".
11933        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
11934        setBundledAppAbi(pkg, apkRoot, apkName);
11935        // pkgSetting might be null during rescan following uninstall of updates
11936        // to a bundled app, so accommodate that possibility.  The settings in
11937        // that case will be established later from the parsed package.
11938        //
11939        // If the settings aren't null, sync them up with what we've just derived.
11940        // note that apkRoot isn't stored in the package settings.
11941        if (pkgSetting != null) {
11942            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11943            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11944        }
11945    }
11946
11947    /**
11948     * Deduces the ABI of a bundled app and sets the relevant fields on the
11949     * parsed pkg object.
11950     *
11951     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
11952     *        under which system libraries are installed.
11953     * @param apkName the name of the installed package.
11954     */
11955    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
11956        final File codeFile = new File(pkg.codePath);
11957
11958        final boolean has64BitLibs;
11959        final boolean has32BitLibs;
11960        if (isApkFile(codeFile)) {
11961            // Monolithic install
11962            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
11963            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
11964        } else {
11965            // Cluster install
11966            final File rootDir = new File(codeFile, LIB_DIR_NAME);
11967            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
11968                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
11969                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
11970                has64BitLibs = (new File(rootDir, isa)).exists();
11971            } else {
11972                has64BitLibs = false;
11973            }
11974            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
11975                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
11976                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
11977                has32BitLibs = (new File(rootDir, isa)).exists();
11978            } else {
11979                has32BitLibs = false;
11980            }
11981        }
11982
11983        if (has64BitLibs && !has32BitLibs) {
11984            // The package has 64 bit libs, but not 32 bit libs. Its primary
11985            // ABI should be 64 bit. We can safely assume here that the bundled
11986            // native libraries correspond to the most preferred ABI in the list.
11987
11988            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11989            pkg.applicationInfo.secondaryCpuAbi = null;
11990        } else if (has32BitLibs && !has64BitLibs) {
11991            // The package has 32 bit libs but not 64 bit libs. Its primary
11992            // ABI should be 32 bit.
11993
11994            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11995            pkg.applicationInfo.secondaryCpuAbi = null;
11996        } else if (has32BitLibs && has64BitLibs) {
11997            // The application has both 64 and 32 bit bundled libraries. We check
11998            // here that the app declares multiArch support, and warn if it doesn't.
11999            //
12000            // We will be lenient here and record both ABIs. The primary will be the
12001            // ABI that's higher on the list, i.e, a device that's configured to prefer
12002            // 64 bit apps will see a 64 bit primary ABI,
12003
12004            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
12005                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
12006            }
12007
12008            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
12009                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12010                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12011            } else {
12012                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12013                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12014            }
12015        } else {
12016            pkg.applicationInfo.primaryCpuAbi = null;
12017            pkg.applicationInfo.secondaryCpuAbi = null;
12018        }
12019    }
12020
12021    private void killApplication(String pkgName, int appId, String reason) {
12022        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
12023    }
12024
12025    private void killApplication(String pkgName, int appId, int userId, String reason) {
12026        // Request the ActivityManager to kill the process(only for existing packages)
12027        // so that we do not end up in a confused state while the user is still using the older
12028        // version of the application while the new one gets installed.
12029        final long token = Binder.clearCallingIdentity();
12030        try {
12031            IActivityManager am = ActivityManager.getService();
12032            if (am != null) {
12033                try {
12034                    am.killApplication(pkgName, appId, userId, reason);
12035                } catch (RemoteException e) {
12036                }
12037            }
12038        } finally {
12039            Binder.restoreCallingIdentity(token);
12040        }
12041    }
12042
12043    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
12044        // Remove the parent package setting
12045        PackageSetting ps = (PackageSetting) pkg.mExtras;
12046        if (ps != null) {
12047            removePackageLI(ps, chatty);
12048        }
12049        // Remove the child package setting
12050        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12051        for (int i = 0; i < childCount; i++) {
12052            PackageParser.Package childPkg = pkg.childPackages.get(i);
12053            ps = (PackageSetting) childPkg.mExtras;
12054            if (ps != null) {
12055                removePackageLI(ps, chatty);
12056            }
12057        }
12058    }
12059
12060    void removePackageLI(PackageSetting ps, boolean chatty) {
12061        if (DEBUG_INSTALL) {
12062            if (chatty)
12063                Log.d(TAG, "Removing package " + ps.name);
12064        }
12065
12066        // writer
12067        synchronized (mPackages) {
12068            mPackages.remove(ps.name);
12069            final PackageParser.Package pkg = ps.pkg;
12070            if (pkg != null) {
12071                cleanPackageDataStructuresLILPw(pkg, chatty);
12072            }
12073        }
12074    }
12075
12076    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
12077        if (DEBUG_INSTALL) {
12078            if (chatty)
12079                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
12080        }
12081
12082        // writer
12083        synchronized (mPackages) {
12084            // Remove the parent package
12085            mPackages.remove(pkg.applicationInfo.packageName);
12086            cleanPackageDataStructuresLILPw(pkg, chatty);
12087
12088            // Remove the child packages
12089            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12090            for (int i = 0; i < childCount; i++) {
12091                PackageParser.Package childPkg = pkg.childPackages.get(i);
12092                mPackages.remove(childPkg.applicationInfo.packageName);
12093                cleanPackageDataStructuresLILPw(childPkg, chatty);
12094            }
12095        }
12096    }
12097
12098    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
12099        int N = pkg.providers.size();
12100        StringBuilder r = null;
12101        int i;
12102        for (i=0; i<N; i++) {
12103            PackageParser.Provider p = pkg.providers.get(i);
12104            mProviders.removeProvider(p);
12105            if (p.info.authority == null) {
12106
12107                /* There was another ContentProvider with this authority when
12108                 * this app was installed so this authority is null,
12109                 * Ignore it as we don't have to unregister the provider.
12110                 */
12111                continue;
12112            }
12113            String names[] = p.info.authority.split(";");
12114            for (int j = 0; j < names.length; j++) {
12115                if (mProvidersByAuthority.get(names[j]) == p) {
12116                    mProvidersByAuthority.remove(names[j]);
12117                    if (DEBUG_REMOVE) {
12118                        if (chatty)
12119                            Log.d(TAG, "Unregistered content provider: " + names[j]
12120                                    + ", className = " + p.info.name + ", isSyncable = "
12121                                    + p.info.isSyncable);
12122                    }
12123                }
12124            }
12125            if (DEBUG_REMOVE && chatty) {
12126                if (r == null) {
12127                    r = new StringBuilder(256);
12128                } else {
12129                    r.append(' ');
12130                }
12131                r.append(p.info.name);
12132            }
12133        }
12134        if (r != null) {
12135            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
12136        }
12137
12138        N = pkg.services.size();
12139        r = null;
12140        for (i=0; i<N; i++) {
12141            PackageParser.Service s = pkg.services.get(i);
12142            mServices.removeService(s);
12143            if (chatty) {
12144                if (r == null) {
12145                    r = new StringBuilder(256);
12146                } else {
12147                    r.append(' ');
12148                }
12149                r.append(s.info.name);
12150            }
12151        }
12152        if (r != null) {
12153            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
12154        }
12155
12156        N = pkg.receivers.size();
12157        r = null;
12158        for (i=0; i<N; i++) {
12159            PackageParser.Activity a = pkg.receivers.get(i);
12160            mReceivers.removeActivity(a, "receiver");
12161            if (DEBUG_REMOVE && chatty) {
12162                if (r == null) {
12163                    r = new StringBuilder(256);
12164                } else {
12165                    r.append(' ');
12166                }
12167                r.append(a.info.name);
12168            }
12169        }
12170        if (r != null) {
12171            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
12172        }
12173
12174        N = pkg.activities.size();
12175        r = null;
12176        for (i=0; i<N; i++) {
12177            PackageParser.Activity a = pkg.activities.get(i);
12178            mActivities.removeActivity(a, "activity");
12179            if (DEBUG_REMOVE && chatty) {
12180                if (r == null) {
12181                    r = new StringBuilder(256);
12182                } else {
12183                    r.append(' ');
12184                }
12185                r.append(a.info.name);
12186            }
12187        }
12188        if (r != null) {
12189            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
12190        }
12191
12192        N = pkg.permissions.size();
12193        r = null;
12194        for (i=0; i<N; i++) {
12195            PackageParser.Permission p = pkg.permissions.get(i);
12196            BasePermission bp = mSettings.mPermissions.get(p.info.name);
12197            if (bp == null) {
12198                bp = mSettings.mPermissionTrees.get(p.info.name);
12199            }
12200            if (bp != null && bp.perm == p) {
12201                bp.perm = null;
12202                if (DEBUG_REMOVE && chatty) {
12203                    if (r == null) {
12204                        r = new StringBuilder(256);
12205                    } else {
12206                        r.append(' ');
12207                    }
12208                    r.append(p.info.name);
12209                }
12210            }
12211            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12212                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
12213                if (appOpPkgs != null) {
12214                    appOpPkgs.remove(pkg.packageName);
12215                }
12216            }
12217        }
12218        if (r != null) {
12219            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12220        }
12221
12222        N = pkg.requestedPermissions.size();
12223        r = null;
12224        for (i=0; i<N; i++) {
12225            String perm = pkg.requestedPermissions.get(i);
12226            BasePermission bp = mSettings.mPermissions.get(perm);
12227            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12228                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
12229                if (appOpPkgs != null) {
12230                    appOpPkgs.remove(pkg.packageName);
12231                    if (appOpPkgs.isEmpty()) {
12232                        mAppOpPermissionPackages.remove(perm);
12233                    }
12234                }
12235            }
12236        }
12237        if (r != null) {
12238            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12239        }
12240
12241        N = pkg.instrumentation.size();
12242        r = null;
12243        for (i=0; i<N; i++) {
12244            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
12245            mInstrumentation.remove(a.getComponentName());
12246            if (DEBUG_REMOVE && chatty) {
12247                if (r == null) {
12248                    r = new StringBuilder(256);
12249                } else {
12250                    r.append(' ');
12251                }
12252                r.append(a.info.name);
12253            }
12254        }
12255        if (r != null) {
12256            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
12257        }
12258
12259        r = null;
12260        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
12261            // Only system apps can hold shared libraries.
12262            if (pkg.libraryNames != null) {
12263                for (i = 0; i < pkg.libraryNames.size(); i++) {
12264                    String name = pkg.libraryNames.get(i);
12265                    if (removeSharedLibraryLPw(name, 0)) {
12266                        if (DEBUG_REMOVE && chatty) {
12267                            if (r == null) {
12268                                r = new StringBuilder(256);
12269                            } else {
12270                                r.append(' ');
12271                            }
12272                            r.append(name);
12273                        }
12274                    }
12275                }
12276            }
12277        }
12278
12279        r = null;
12280
12281        // Any package can hold static shared libraries.
12282        if (pkg.staticSharedLibName != null) {
12283            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
12284                if (DEBUG_REMOVE && chatty) {
12285                    if (r == null) {
12286                        r = new StringBuilder(256);
12287                    } else {
12288                        r.append(' ');
12289                    }
12290                    r.append(pkg.staticSharedLibName);
12291                }
12292            }
12293        }
12294
12295        if (r != null) {
12296            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
12297        }
12298    }
12299
12300    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
12301        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
12302            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
12303                return true;
12304            }
12305        }
12306        return false;
12307    }
12308
12309    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
12310    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
12311    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
12312
12313    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
12314        // Update the parent permissions
12315        updatePermissionsLPw(pkg.packageName, pkg, flags);
12316        // Update the child permissions
12317        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12318        for (int i = 0; i < childCount; i++) {
12319            PackageParser.Package childPkg = pkg.childPackages.get(i);
12320            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
12321        }
12322    }
12323
12324    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
12325            int flags) {
12326        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
12327        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
12328    }
12329
12330    private void updatePermissionsLPw(String changingPkg,
12331            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
12332        // Make sure there are no dangling permission trees.
12333        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
12334        while (it.hasNext()) {
12335            final BasePermission bp = it.next();
12336            if (bp.packageSetting == null) {
12337                // We may not yet have parsed the package, so just see if
12338                // we still know about its settings.
12339                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12340            }
12341            if (bp.packageSetting == null) {
12342                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
12343                        + " from package " + bp.sourcePackage);
12344                it.remove();
12345            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12346                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12347                    Slog.i(TAG, "Removing old permission tree: " + bp.name
12348                            + " from package " + bp.sourcePackage);
12349                    flags |= UPDATE_PERMISSIONS_ALL;
12350                    it.remove();
12351                }
12352            }
12353        }
12354
12355        // Make sure all dynamic permissions have been assigned to a package,
12356        // and make sure there are no dangling permissions.
12357        it = mSettings.mPermissions.values().iterator();
12358        while (it.hasNext()) {
12359            final BasePermission bp = it.next();
12360            if (bp.type == BasePermission.TYPE_DYNAMIC) {
12361                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
12362                        + bp.name + " pkg=" + bp.sourcePackage
12363                        + " info=" + bp.pendingInfo);
12364                if (bp.packageSetting == null && bp.pendingInfo != null) {
12365                    final BasePermission tree = findPermissionTreeLP(bp.name);
12366                    if (tree != null && tree.perm != null) {
12367                        bp.packageSetting = tree.packageSetting;
12368                        bp.perm = new PackageParser.Permission(tree.perm.owner,
12369                                new PermissionInfo(bp.pendingInfo));
12370                        bp.perm.info.packageName = tree.perm.info.packageName;
12371                        bp.perm.info.name = bp.name;
12372                        bp.uid = tree.uid;
12373                    }
12374                }
12375            }
12376            if (bp.packageSetting == null) {
12377                // We may not yet have parsed the package, so just see if
12378                // we still know about its settings.
12379                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12380            }
12381            if (bp.packageSetting == null) {
12382                Slog.w(TAG, "Removing dangling permission: " + bp.name
12383                        + " from package " + bp.sourcePackage);
12384                it.remove();
12385            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12386                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12387                    Slog.i(TAG, "Removing old permission: " + bp.name
12388                            + " from package " + bp.sourcePackage);
12389                    flags |= UPDATE_PERMISSIONS_ALL;
12390                    it.remove();
12391                }
12392            }
12393        }
12394
12395        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
12396        // Now update the permissions for all packages, in particular
12397        // replace the granted permissions of the system packages.
12398        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
12399            for (PackageParser.Package pkg : mPackages.values()) {
12400                if (pkg != pkgInfo) {
12401                    // Only replace for packages on requested volume
12402                    final String volumeUuid = getVolumeUuidForPackage(pkg);
12403                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
12404                            && Objects.equals(replaceVolumeUuid, volumeUuid);
12405                    grantPermissionsLPw(pkg, replace, changingPkg);
12406                }
12407            }
12408        }
12409
12410        if (pkgInfo != null) {
12411            // Only replace for packages on requested volume
12412            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
12413            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
12414                    && Objects.equals(replaceVolumeUuid, volumeUuid);
12415            grantPermissionsLPw(pkgInfo, replace, changingPkg);
12416        }
12417        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12418    }
12419
12420    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
12421            String packageOfInterest) {
12422        // IMPORTANT: There are two types of permissions: install and runtime.
12423        // Install time permissions are granted when the app is installed to
12424        // all device users and users added in the future. Runtime permissions
12425        // are granted at runtime explicitly to specific users. Normal and signature
12426        // protected permissions are install time permissions. Dangerous permissions
12427        // are install permissions if the app's target SDK is Lollipop MR1 or older,
12428        // otherwise they are runtime permissions. This function does not manage
12429        // runtime permissions except for the case an app targeting Lollipop MR1
12430        // being upgraded to target a newer SDK, in which case dangerous permissions
12431        // are transformed from install time to runtime ones.
12432
12433        final PackageSetting ps = (PackageSetting) pkg.mExtras;
12434        if (ps == null) {
12435            return;
12436        }
12437
12438        PermissionsState permissionsState = ps.getPermissionsState();
12439        PermissionsState origPermissions = permissionsState;
12440
12441        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
12442
12443        boolean runtimePermissionsRevoked = false;
12444        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
12445
12446        boolean changedInstallPermission = false;
12447
12448        if (replace) {
12449            ps.installPermissionsFixed = false;
12450            if (!ps.isSharedUser()) {
12451                origPermissions = new PermissionsState(permissionsState);
12452                permissionsState.reset();
12453            } else {
12454                // We need to know only about runtime permission changes since the
12455                // calling code always writes the install permissions state but
12456                // the runtime ones are written only if changed. The only cases of
12457                // changed runtime permissions here are promotion of an install to
12458                // runtime and revocation of a runtime from a shared user.
12459                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
12460                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
12461                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
12462                    runtimePermissionsRevoked = true;
12463                }
12464            }
12465        }
12466
12467        permissionsState.setGlobalGids(mGlobalGids);
12468
12469        final int N = pkg.requestedPermissions.size();
12470        for (int i=0; i<N; i++) {
12471            final String name = pkg.requestedPermissions.get(i);
12472            final BasePermission bp = mSettings.mPermissions.get(name);
12473            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
12474                    >= Build.VERSION_CODES.M;
12475
12476            if (DEBUG_INSTALL) {
12477                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
12478            }
12479
12480            if (bp == null || bp.packageSetting == null) {
12481                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
12482                    if (DEBUG_PERMISSIONS) {
12483                        Slog.i(TAG, "Unknown permission " + name
12484                                + " in package " + pkg.packageName);
12485                    }
12486                }
12487                continue;
12488            }
12489
12490
12491            // Limit ephemeral apps to ephemeral allowed permissions.
12492            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
12493                if (DEBUG_PERMISSIONS) {
12494                    Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
12495                            + pkg.packageName);
12496                }
12497                continue;
12498            }
12499
12500            if (bp.isRuntimeOnly() && !appSupportsRuntimePermissions) {
12501                if (DEBUG_PERMISSIONS) {
12502                    Log.i(TAG, "Denying runtime-only permission " + bp.name + " for package "
12503                            + pkg.packageName);
12504                }
12505                continue;
12506            }
12507
12508            final String perm = bp.name;
12509            boolean allowedSig = false;
12510            int grant = GRANT_DENIED;
12511
12512            // Keep track of app op permissions.
12513            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12514                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
12515                if (pkgs == null) {
12516                    pkgs = new ArraySet<>();
12517                    mAppOpPermissionPackages.put(bp.name, pkgs);
12518                }
12519                pkgs.add(pkg.packageName);
12520            }
12521
12522            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
12523            switch (level) {
12524                case PermissionInfo.PROTECTION_NORMAL: {
12525                    // For all apps normal permissions are install time ones.
12526                    grant = GRANT_INSTALL;
12527                } break;
12528
12529                case PermissionInfo.PROTECTION_DANGEROUS: {
12530                    // If a permission review is required for legacy apps we represent
12531                    // their permissions as always granted runtime ones since we need
12532                    // to keep the review required permission flag per user while an
12533                    // install permission's state is shared across all users.
12534                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
12535                        // For legacy apps dangerous permissions are install time ones.
12536                        grant = GRANT_INSTALL;
12537                    } else if (origPermissions.hasInstallPermission(bp.name)) {
12538                        // For legacy apps that became modern, install becomes runtime.
12539                        grant = GRANT_UPGRADE;
12540                    } else if (mPromoteSystemApps
12541                            && isSystemApp(ps)
12542                            && mExistingSystemPackages.contains(ps.name)) {
12543                        // For legacy system apps, install becomes runtime.
12544                        // We cannot check hasInstallPermission() for system apps since those
12545                        // permissions were granted implicitly and not persisted pre-M.
12546                        grant = GRANT_UPGRADE;
12547                    } else {
12548                        // For modern apps keep runtime permissions unchanged.
12549                        grant = GRANT_RUNTIME;
12550                    }
12551                } break;
12552
12553                case PermissionInfo.PROTECTION_SIGNATURE: {
12554                    // For all apps signature permissions are install time ones.
12555                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
12556                    if (allowedSig) {
12557                        grant = GRANT_INSTALL;
12558                    }
12559                } break;
12560            }
12561
12562            if (DEBUG_PERMISSIONS) {
12563                Slog.i(TAG, "Granting permission " + perm + " to package " + pkg.packageName);
12564            }
12565
12566            if (grant != GRANT_DENIED) {
12567                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
12568                    // If this is an existing, non-system package, then
12569                    // we can't add any new permissions to it.
12570                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
12571                        // Except...  if this is a permission that was added
12572                        // to the platform (note: need to only do this when
12573                        // updating the platform).
12574                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
12575                            grant = GRANT_DENIED;
12576                        }
12577                    }
12578                }
12579
12580                switch (grant) {
12581                    case GRANT_INSTALL: {
12582                        // Revoke this as runtime permission to handle the case of
12583                        // a runtime permission being downgraded to an install one.
12584                        // Also in permission review mode we keep dangerous permissions
12585                        // for legacy apps
12586                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12587                            if (origPermissions.getRuntimePermissionState(
12588                                    bp.name, userId) != null) {
12589                                // Revoke the runtime permission and clear the flags.
12590                                origPermissions.revokeRuntimePermission(bp, userId);
12591                                origPermissions.updatePermissionFlags(bp, userId,
12592                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
12593                                // If we revoked a permission permission, we have to write.
12594                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12595                                        changedRuntimePermissionUserIds, userId);
12596                            }
12597                        }
12598                        // Grant an install permission.
12599                        if (permissionsState.grantInstallPermission(bp) !=
12600                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
12601                            changedInstallPermission = true;
12602                        }
12603                    } break;
12604
12605                    case GRANT_RUNTIME: {
12606                        // Grant previously granted runtime permissions.
12607                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12608                            PermissionState permissionState = origPermissions
12609                                    .getRuntimePermissionState(bp.name, userId);
12610                            int flags = permissionState != null
12611                                    ? permissionState.getFlags() : 0;
12612                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
12613                                // Don't propagate the permission in a permission review mode if
12614                                // the former was revoked, i.e. marked to not propagate on upgrade.
12615                                // Note that in a permission review mode install permissions are
12616                                // represented as constantly granted runtime ones since we need to
12617                                // keep a per user state associated with the permission. Also the
12618                                // revoke on upgrade flag is no longer applicable and is reset.
12619                                final boolean revokeOnUpgrade = (flags & PackageManager
12620                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
12621                                if (revokeOnUpgrade) {
12622                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
12623                                    // Since we changed the flags, we have to write.
12624                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12625                                            changedRuntimePermissionUserIds, userId);
12626                                }
12627                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
12628                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
12629                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
12630                                        // If we cannot put the permission as it was,
12631                                        // we have to write.
12632                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12633                                                changedRuntimePermissionUserIds, userId);
12634                                    }
12635                                }
12636
12637                                // If the app supports runtime permissions no need for a review.
12638                                if (mPermissionReviewRequired
12639                                        && appSupportsRuntimePermissions
12640                                        && (flags & PackageManager
12641                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
12642                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
12643                                    // Since we changed the flags, we have to write.
12644                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12645                                            changedRuntimePermissionUserIds, userId);
12646                                }
12647                            } else if (mPermissionReviewRequired
12648                                    && !appSupportsRuntimePermissions) {
12649                                // For legacy apps that need a permission review, every new
12650                                // runtime permission is granted but it is pending a review.
12651                                // We also need to review only platform defined runtime
12652                                // permissions as these are the only ones the platform knows
12653                                // how to disable the API to simulate revocation as legacy
12654                                // apps don't expect to run with revoked permissions.
12655                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
12656                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
12657                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
12658                                        // We changed the flags, hence have to write.
12659                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12660                                                changedRuntimePermissionUserIds, userId);
12661                                    }
12662                                }
12663                                if (permissionsState.grantRuntimePermission(bp, userId)
12664                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
12665                                    // We changed the permission, hence have to write.
12666                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12667                                            changedRuntimePermissionUserIds, userId);
12668                                }
12669                            }
12670                            // Propagate the permission flags.
12671                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
12672                        }
12673                    } break;
12674
12675                    case GRANT_UPGRADE: {
12676                        // Grant runtime permissions for a previously held install permission.
12677                        PermissionState permissionState = origPermissions
12678                                .getInstallPermissionState(bp.name);
12679                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
12680
12681                        if (origPermissions.revokeInstallPermission(bp)
12682                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
12683                            // We will be transferring the permission flags, so clear them.
12684                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
12685                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
12686                            changedInstallPermission = true;
12687                        }
12688
12689                        // If the permission is not to be promoted to runtime we ignore it and
12690                        // also its other flags as they are not applicable to install permissions.
12691                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
12692                            for (int userId : currentUserIds) {
12693                                if (permissionsState.grantRuntimePermission(bp, userId) !=
12694                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
12695                                    // Transfer the permission flags.
12696                                    permissionsState.updatePermissionFlags(bp, userId,
12697                                            flags, flags);
12698                                    // If we granted the permission, we have to write.
12699                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12700                                            changedRuntimePermissionUserIds, userId);
12701                                }
12702                            }
12703                        }
12704                    } break;
12705
12706                    default: {
12707                        if (packageOfInterest == null
12708                                || packageOfInterest.equals(pkg.packageName)) {
12709                            if (DEBUG_PERMISSIONS) {
12710                                Slog.i(TAG, "Not granting permission " + perm
12711                                        + " to package " + pkg.packageName
12712                                        + " because it was previously installed without");
12713                            }
12714                        }
12715                    } break;
12716                }
12717            } else {
12718                if (permissionsState.revokeInstallPermission(bp) !=
12719                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
12720                    // Also drop the permission flags.
12721                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
12722                            PackageManager.MASK_PERMISSION_FLAGS, 0);
12723                    changedInstallPermission = true;
12724                    Slog.i(TAG, "Un-granting permission " + perm
12725                            + " from package " + pkg.packageName
12726                            + " (protectionLevel=" + bp.protectionLevel
12727                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
12728                            + ")");
12729                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
12730                    // Don't print warning for app op permissions, since it is fine for them
12731                    // not to be granted, there is a UI for the user to decide.
12732                    if (DEBUG_PERMISSIONS
12733                            && (packageOfInterest == null
12734                                    || packageOfInterest.equals(pkg.packageName))) {
12735                        Slog.i(TAG, "Not granting permission " + perm
12736                                + " to package " + pkg.packageName
12737                                + " (protectionLevel=" + bp.protectionLevel
12738                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
12739                                + ")");
12740                    }
12741                }
12742            }
12743        }
12744
12745        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
12746                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
12747            // This is the first that we have heard about this package, so the
12748            // permissions we have now selected are fixed until explicitly
12749            // changed.
12750            ps.installPermissionsFixed = true;
12751        }
12752
12753        // Persist the runtime permissions state for users with changes. If permissions
12754        // were revoked because no app in the shared user declares them we have to
12755        // write synchronously to avoid losing runtime permissions state.
12756        for (int userId : changedRuntimePermissionUserIds) {
12757            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
12758        }
12759    }
12760
12761    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
12762        boolean allowed = false;
12763        final int NP = PackageParser.NEW_PERMISSIONS.length;
12764        for (int ip=0; ip<NP; ip++) {
12765            final PackageParser.NewPermissionInfo npi
12766                    = PackageParser.NEW_PERMISSIONS[ip];
12767            if (npi.name.equals(perm)
12768                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
12769                allowed = true;
12770                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
12771                        + pkg.packageName);
12772                break;
12773            }
12774        }
12775        return allowed;
12776    }
12777
12778    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
12779            BasePermission bp, PermissionsState origPermissions) {
12780        boolean privilegedPermission = (bp.protectionLevel
12781                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
12782        boolean privappPermissionsDisable =
12783                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
12784        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
12785        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
12786        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
12787                && !platformPackage && platformPermission) {
12788            ArraySet<String> wlPermissions = SystemConfig.getInstance()
12789                    .getPrivAppPermissions(pkg.packageName);
12790            boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
12791            if (!whitelisted) {
12792                Slog.w(TAG, "Privileged permission " + perm + " for package "
12793                        + pkg.packageName + " - not in privapp-permissions whitelist");
12794                // Only report violations for apps on system image
12795                if (!mSystemReady && !pkg.isUpdatedSystemApp()) {
12796                    if (mPrivappPermissionsViolations == null) {
12797                        mPrivappPermissionsViolations = new ArraySet<>();
12798                    }
12799                    mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
12800                }
12801                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
12802                    return false;
12803                }
12804            }
12805        }
12806        boolean allowed = (compareSignatures(
12807                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
12808                        == PackageManager.SIGNATURE_MATCH)
12809                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
12810                        == PackageManager.SIGNATURE_MATCH);
12811        if (!allowed && privilegedPermission) {
12812            if (isSystemApp(pkg)) {
12813                // For updated system applications, a system permission
12814                // is granted only if it had been defined by the original application.
12815                if (pkg.isUpdatedSystemApp()) {
12816                    final PackageSetting sysPs = mSettings
12817                            .getDisabledSystemPkgLPr(pkg.packageName);
12818                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
12819                        // If the original was granted this permission, we take
12820                        // that grant decision as read and propagate it to the
12821                        // update.
12822                        if (sysPs.isPrivileged()) {
12823                            allowed = true;
12824                        }
12825                    } else {
12826                        // The system apk may have been updated with an older
12827                        // version of the one on the data partition, but which
12828                        // granted a new system permission that it didn't have
12829                        // before.  In this case we do want to allow the app to
12830                        // now get the new permission if the ancestral apk is
12831                        // privileged to get it.
12832                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
12833                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
12834                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
12835                                    allowed = true;
12836                                    break;
12837                                }
12838                            }
12839                        }
12840                        // Also if a privileged parent package on the system image or any of
12841                        // its children requested a privileged permission, the updated child
12842                        // packages can also get the permission.
12843                        if (pkg.parentPackage != null) {
12844                            final PackageSetting disabledSysParentPs = mSettings
12845                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
12846                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
12847                                    && disabledSysParentPs.isPrivileged()) {
12848                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
12849                                    allowed = true;
12850                                } else if (disabledSysParentPs.pkg.childPackages != null) {
12851                                    final int count = disabledSysParentPs.pkg.childPackages.size();
12852                                    for (int i = 0; i < count; i++) {
12853                                        PackageParser.Package disabledSysChildPkg =
12854                                                disabledSysParentPs.pkg.childPackages.get(i);
12855                                        if (isPackageRequestingPermission(disabledSysChildPkg,
12856                                                perm)) {
12857                                            allowed = true;
12858                                            break;
12859                                        }
12860                                    }
12861                                }
12862                            }
12863                        }
12864                    }
12865                } else {
12866                    allowed = isPrivilegedApp(pkg);
12867                }
12868            }
12869        }
12870        if (!allowed) {
12871            if (!allowed && (bp.protectionLevel
12872                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
12873                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
12874                // If this was a previously normal/dangerous permission that got moved
12875                // to a system permission as part of the runtime permission redesign, then
12876                // we still want to blindly grant it to old apps.
12877                allowed = true;
12878            }
12879            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
12880                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
12881                // If this permission is to be granted to the system installer and
12882                // this app is an installer, then it gets the permission.
12883                allowed = true;
12884            }
12885            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
12886                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
12887                // If this permission is to be granted to the system verifier and
12888                // this app is a verifier, then it gets the permission.
12889                allowed = true;
12890            }
12891            if (!allowed && (bp.protectionLevel
12892                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
12893                    && isSystemApp(pkg)) {
12894                // Any pre-installed system app is allowed to get this permission.
12895                allowed = true;
12896            }
12897            if (!allowed && (bp.protectionLevel
12898                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
12899                // For development permissions, a development permission
12900                // is granted only if it was already granted.
12901                allowed = origPermissions.hasInstallPermission(perm);
12902            }
12903            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
12904                    && pkg.packageName.equals(mSetupWizardPackage)) {
12905                // If this permission is to be granted to the system setup wizard and
12906                // this app is a setup wizard, then it gets the permission.
12907                allowed = true;
12908            }
12909        }
12910        return allowed;
12911    }
12912
12913    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
12914        final int permCount = pkg.requestedPermissions.size();
12915        for (int j = 0; j < permCount; j++) {
12916            String requestedPermission = pkg.requestedPermissions.get(j);
12917            if (permission.equals(requestedPermission)) {
12918                return true;
12919            }
12920        }
12921        return false;
12922    }
12923
12924    final class ActivityIntentResolver
12925            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
12926        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12927                boolean defaultOnly, int userId) {
12928            if (!sUserManager.exists(userId)) return null;
12929            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
12930            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12931        }
12932
12933        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12934                int userId) {
12935            if (!sUserManager.exists(userId)) return null;
12936            mFlags = flags;
12937            return super.queryIntent(intent, resolvedType,
12938                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12939                    userId);
12940        }
12941
12942        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12943                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
12944            if (!sUserManager.exists(userId)) return null;
12945            if (packageActivities == null) {
12946                return null;
12947            }
12948            mFlags = flags;
12949            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12950            final int N = packageActivities.size();
12951            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
12952                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
12953
12954            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
12955            for (int i = 0; i < N; ++i) {
12956                intentFilters = packageActivities.get(i).intents;
12957                if (intentFilters != null && intentFilters.size() > 0) {
12958                    PackageParser.ActivityIntentInfo[] array =
12959                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
12960                    intentFilters.toArray(array);
12961                    listCut.add(array);
12962                }
12963            }
12964            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12965        }
12966
12967        /**
12968         * Finds a privileged activity that matches the specified activity names.
12969         */
12970        private PackageParser.Activity findMatchingActivity(
12971                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
12972            for (PackageParser.Activity sysActivity : activityList) {
12973                if (sysActivity.info.name.equals(activityInfo.name)) {
12974                    return sysActivity;
12975                }
12976                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
12977                    return sysActivity;
12978                }
12979                if (sysActivity.info.targetActivity != null) {
12980                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
12981                        return sysActivity;
12982                    }
12983                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
12984                        return sysActivity;
12985                    }
12986                }
12987            }
12988            return null;
12989        }
12990
12991        public class IterGenerator<E> {
12992            public Iterator<E> generate(ActivityIntentInfo info) {
12993                return null;
12994            }
12995        }
12996
12997        public class ActionIterGenerator extends IterGenerator<String> {
12998            @Override
12999            public Iterator<String> generate(ActivityIntentInfo info) {
13000                return info.actionsIterator();
13001            }
13002        }
13003
13004        public class CategoriesIterGenerator extends IterGenerator<String> {
13005            @Override
13006            public Iterator<String> generate(ActivityIntentInfo info) {
13007                return info.categoriesIterator();
13008            }
13009        }
13010
13011        public class SchemesIterGenerator extends IterGenerator<String> {
13012            @Override
13013            public Iterator<String> generate(ActivityIntentInfo info) {
13014                return info.schemesIterator();
13015            }
13016        }
13017
13018        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
13019            @Override
13020            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
13021                return info.authoritiesIterator();
13022            }
13023        }
13024
13025        /**
13026         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
13027         * MODIFIED. Do not pass in a list that should not be changed.
13028         */
13029        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
13030                IterGenerator<T> generator, Iterator<T> searchIterator) {
13031            // loop through the set of actions; every one must be found in the intent filter
13032            while (searchIterator.hasNext()) {
13033                // we must have at least one filter in the list to consider a match
13034                if (intentList.size() == 0) {
13035                    break;
13036                }
13037
13038                final T searchAction = searchIterator.next();
13039
13040                // loop through the set of intent filters
13041                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
13042                while (intentIter.hasNext()) {
13043                    final ActivityIntentInfo intentInfo = intentIter.next();
13044                    boolean selectionFound = false;
13045
13046                    // loop through the intent filter's selection criteria; at least one
13047                    // of them must match the searched criteria
13048                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
13049                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
13050                        final T intentSelection = intentSelectionIter.next();
13051                        if (intentSelection != null && intentSelection.equals(searchAction)) {
13052                            selectionFound = true;
13053                            break;
13054                        }
13055                    }
13056
13057                    // the selection criteria wasn't found in this filter's set; this filter
13058                    // is not a potential match
13059                    if (!selectionFound) {
13060                        intentIter.remove();
13061                    }
13062                }
13063            }
13064        }
13065
13066        private boolean isProtectedAction(ActivityIntentInfo filter) {
13067            final Iterator<String> actionsIter = filter.actionsIterator();
13068            while (actionsIter != null && actionsIter.hasNext()) {
13069                final String filterAction = actionsIter.next();
13070                if (PROTECTED_ACTIONS.contains(filterAction)) {
13071                    return true;
13072                }
13073            }
13074            return false;
13075        }
13076
13077        /**
13078         * Adjusts the priority of the given intent filter according to policy.
13079         * <p>
13080         * <ul>
13081         * <li>The priority for non privileged applications is capped to '0'</li>
13082         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
13083         * <li>The priority for unbundled updates to privileged applications is capped to the
13084         *      priority defined on the system partition</li>
13085         * </ul>
13086         * <p>
13087         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
13088         * allowed to obtain any priority on any action.
13089         */
13090        private void adjustPriority(
13091                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
13092            // nothing to do; priority is fine as-is
13093            if (intent.getPriority() <= 0) {
13094                return;
13095            }
13096
13097            final ActivityInfo activityInfo = intent.activity.info;
13098            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
13099
13100            final boolean privilegedApp =
13101                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
13102            if (!privilegedApp) {
13103                // non-privileged applications can never define a priority >0
13104                if (DEBUG_FILTERS) {
13105                    Slog.i(TAG, "Non-privileged app; 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            if (systemActivities == null) {
13115                // the system package is not disabled; we're parsing the system partition
13116                if (isProtectedAction(intent)) {
13117                    if (mDeferProtectedFilters) {
13118                        // We can't deal with these just yet. No component should ever obtain a
13119                        // >0 priority for a protected actions, with ONE exception -- the setup
13120                        // wizard. The setup wizard, however, cannot be known until we're able to
13121                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
13122                        // until all intent filters have been processed. Chicken, meet egg.
13123                        // Let the filter temporarily have a high priority and rectify the
13124                        // priorities after all system packages have been scanned.
13125                        mProtectedFilters.add(intent);
13126                        if (DEBUG_FILTERS) {
13127                            Slog.i(TAG, "Protected action; save for later;"
13128                                    + " package: " + applicationInfo.packageName
13129                                    + " activity: " + intent.activity.className
13130                                    + " origPrio: " + intent.getPriority());
13131                        }
13132                        return;
13133                    } else {
13134                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
13135                            Slog.i(TAG, "No setup wizard;"
13136                                + " All protected intents capped to priority 0");
13137                        }
13138                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
13139                            if (DEBUG_FILTERS) {
13140                                Slog.i(TAG, "Found setup wizard;"
13141                                    + " allow priority " + intent.getPriority() + ";"
13142                                    + " package: " + intent.activity.info.packageName
13143                                    + " activity: " + intent.activity.className
13144                                    + " priority: " + intent.getPriority());
13145                            }
13146                            // setup wizard gets whatever it wants
13147                            return;
13148                        }
13149                        if (DEBUG_FILTERS) {
13150                            Slog.i(TAG, "Protected action; cap priority to 0;"
13151                                    + " package: " + intent.activity.info.packageName
13152                                    + " activity: " + intent.activity.className
13153                                    + " origPrio: " + intent.getPriority());
13154                        }
13155                        intent.setPriority(0);
13156                        return;
13157                    }
13158                }
13159                // privileged apps on the system image get whatever priority they request
13160                return;
13161            }
13162
13163            // privileged app unbundled update ... try to find the same activity
13164            final PackageParser.Activity foundActivity =
13165                    findMatchingActivity(systemActivities, activityInfo);
13166            if (foundActivity == null) {
13167                // this is a new activity; it cannot obtain >0 priority
13168                if (DEBUG_FILTERS) {
13169                    Slog.i(TAG, "New activity; cap priority to 0;"
13170                            + " package: " + applicationInfo.packageName
13171                            + " activity: " + intent.activity.className
13172                            + " origPrio: " + intent.getPriority());
13173                }
13174                intent.setPriority(0);
13175                return;
13176            }
13177
13178            // found activity, now check for filter equivalence
13179
13180            // a shallow copy is enough; we modify the list, not its contents
13181            final List<ActivityIntentInfo> intentListCopy =
13182                    new ArrayList<>(foundActivity.intents);
13183            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
13184
13185            // find matching action subsets
13186            final Iterator<String> actionsIterator = intent.actionsIterator();
13187            if (actionsIterator != null) {
13188                getIntentListSubset(
13189                        intentListCopy, new ActionIterGenerator(), actionsIterator);
13190                if (intentListCopy.size() == 0) {
13191                    // no more intents to match; we're not equivalent
13192                    if (DEBUG_FILTERS) {
13193                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
13194                                + " package: " + applicationInfo.packageName
13195                                + " activity: " + intent.activity.className
13196                                + " origPrio: " + intent.getPriority());
13197                    }
13198                    intent.setPriority(0);
13199                    return;
13200                }
13201            }
13202
13203            // find matching category subsets
13204            final Iterator<String> categoriesIterator = intent.categoriesIterator();
13205            if (categoriesIterator != null) {
13206                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
13207                        categoriesIterator);
13208                if (intentListCopy.size() == 0) {
13209                    // no more intents to match; we're not equivalent
13210                    if (DEBUG_FILTERS) {
13211                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
13212                                + " package: " + applicationInfo.packageName
13213                                + " activity: " + intent.activity.className
13214                                + " origPrio: " + intent.getPriority());
13215                    }
13216                    intent.setPriority(0);
13217                    return;
13218                }
13219            }
13220
13221            // find matching schemes subsets
13222            final Iterator<String> schemesIterator = intent.schemesIterator();
13223            if (schemesIterator != null) {
13224                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
13225                        schemesIterator);
13226                if (intentListCopy.size() == 0) {
13227                    // no more intents to match; we're not equivalent
13228                    if (DEBUG_FILTERS) {
13229                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
13230                                + " package: " + applicationInfo.packageName
13231                                + " activity: " + intent.activity.className
13232                                + " origPrio: " + intent.getPriority());
13233                    }
13234                    intent.setPriority(0);
13235                    return;
13236                }
13237            }
13238
13239            // find matching authorities subsets
13240            final Iterator<IntentFilter.AuthorityEntry>
13241                    authoritiesIterator = intent.authoritiesIterator();
13242            if (authoritiesIterator != null) {
13243                getIntentListSubset(intentListCopy,
13244                        new AuthoritiesIterGenerator(),
13245                        authoritiesIterator);
13246                if (intentListCopy.size() == 0) {
13247                    // no more intents to match; we're not equivalent
13248                    if (DEBUG_FILTERS) {
13249                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
13250                                + " package: " + applicationInfo.packageName
13251                                + " activity: " + intent.activity.className
13252                                + " origPrio: " + intent.getPriority());
13253                    }
13254                    intent.setPriority(0);
13255                    return;
13256                }
13257            }
13258
13259            // we found matching filter(s); app gets the max priority of all intents
13260            int cappedPriority = 0;
13261            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
13262                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
13263            }
13264            if (intent.getPriority() > cappedPriority) {
13265                if (DEBUG_FILTERS) {
13266                    Slog.i(TAG, "Found matching filter(s);"
13267                            + " cap priority to " + cappedPriority + ";"
13268                            + " package: " + applicationInfo.packageName
13269                            + " activity: " + intent.activity.className
13270                            + " origPrio: " + intent.getPriority());
13271                }
13272                intent.setPriority(cappedPriority);
13273                return;
13274            }
13275            // all this for nothing; the requested priority was <= what was on the system
13276        }
13277
13278        public final void addActivity(PackageParser.Activity a, String type) {
13279            mActivities.put(a.getComponentName(), a);
13280            if (DEBUG_SHOW_INFO)
13281                Log.v(
13282                TAG, "  " + type + " " +
13283                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
13284            if (DEBUG_SHOW_INFO)
13285                Log.v(TAG, "    Class=" + a.info.name);
13286            final int NI = a.intents.size();
13287            for (int j=0; j<NI; j++) {
13288                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13289                if ("activity".equals(type)) {
13290                    final PackageSetting ps =
13291                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
13292                    final List<PackageParser.Activity> systemActivities =
13293                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
13294                    adjustPriority(systemActivities, intent);
13295                }
13296                if (DEBUG_SHOW_INFO) {
13297                    Log.v(TAG, "    IntentFilter:");
13298                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13299                }
13300                if (!intent.debugCheck()) {
13301                    Log.w(TAG, "==> For Activity " + a.info.name);
13302                }
13303                addFilter(intent);
13304            }
13305        }
13306
13307        public final void removeActivity(PackageParser.Activity a, String type) {
13308            mActivities.remove(a.getComponentName());
13309            if (DEBUG_SHOW_INFO) {
13310                Log.v(TAG, "  " + type + " "
13311                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
13312                                : a.info.name) + ":");
13313                Log.v(TAG, "    Class=" + a.info.name);
13314            }
13315            final int NI = a.intents.size();
13316            for (int j=0; j<NI; j++) {
13317                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13318                if (DEBUG_SHOW_INFO) {
13319                    Log.v(TAG, "    IntentFilter:");
13320                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13321                }
13322                removeFilter(intent);
13323            }
13324        }
13325
13326        @Override
13327        protected boolean allowFilterResult(
13328                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
13329            ActivityInfo filterAi = filter.activity.info;
13330            for (int i=dest.size()-1; i>=0; i--) {
13331                ActivityInfo destAi = dest.get(i).activityInfo;
13332                if (destAi.name == filterAi.name
13333                        && destAi.packageName == filterAi.packageName) {
13334                    return false;
13335                }
13336            }
13337            return true;
13338        }
13339
13340        @Override
13341        protected ActivityIntentInfo[] newArray(int size) {
13342            return new ActivityIntentInfo[size];
13343        }
13344
13345        @Override
13346        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
13347            if (!sUserManager.exists(userId)) return true;
13348            PackageParser.Package p = filter.activity.owner;
13349            if (p != null) {
13350                PackageSetting ps = (PackageSetting)p.mExtras;
13351                if (ps != null) {
13352                    // System apps are never considered stopped for purposes of
13353                    // filtering, because there may be no way for the user to
13354                    // actually re-launch them.
13355                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
13356                            && ps.getStopped(userId);
13357                }
13358            }
13359            return false;
13360        }
13361
13362        @Override
13363        protected boolean isPackageForFilter(String packageName,
13364                PackageParser.ActivityIntentInfo info) {
13365            return packageName.equals(info.activity.owner.packageName);
13366        }
13367
13368        @Override
13369        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
13370                int match, int userId) {
13371            if (!sUserManager.exists(userId)) return null;
13372            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
13373                return null;
13374            }
13375            final PackageParser.Activity activity = info.activity;
13376            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
13377            if (ps == null) {
13378                return null;
13379            }
13380            final PackageUserState userState = ps.readUserState(userId);
13381            ActivityInfo ai =
13382                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
13383            if (ai == null) {
13384                return null;
13385            }
13386            final boolean matchExplicitlyVisibleOnly =
13387                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
13388            final boolean matchVisibleToInstantApp =
13389                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13390            final boolean componentVisible =
13391                    matchVisibleToInstantApp
13392                    && info.isVisibleToInstantApp()
13393                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
13394            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13395            // throw out filters that aren't visible to ephemeral apps
13396            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
13397                return null;
13398            }
13399            // throw out instant app filters if we're not explicitly requesting them
13400            if (!matchInstantApp && userState.instantApp) {
13401                return null;
13402            }
13403            // throw out instant app filters if updates are available; will trigger
13404            // instant app resolution
13405            if (userState.instantApp && ps.isUpdateAvailable()) {
13406                return null;
13407            }
13408            final ResolveInfo res = new ResolveInfo();
13409            res.activityInfo = ai;
13410            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13411                res.filter = info;
13412            }
13413            if (info != null) {
13414                res.handleAllWebDataURI = info.handleAllWebDataURI();
13415            }
13416            res.priority = info.getPriority();
13417            res.preferredOrder = activity.owner.mPreferredOrder;
13418            //System.out.println("Result: " + res.activityInfo.className +
13419            //                   " = " + res.priority);
13420            res.match = match;
13421            res.isDefault = info.hasDefault;
13422            res.labelRes = info.labelRes;
13423            res.nonLocalizedLabel = info.nonLocalizedLabel;
13424            if (userNeedsBadging(userId)) {
13425                res.noResourceId = true;
13426            } else {
13427                res.icon = info.icon;
13428            }
13429            res.iconResourceId = info.icon;
13430            res.system = res.activityInfo.applicationInfo.isSystemApp();
13431            res.isInstantAppAvailable = userState.instantApp;
13432            return res;
13433        }
13434
13435        @Override
13436        protected void sortResults(List<ResolveInfo> results) {
13437            Collections.sort(results, mResolvePrioritySorter);
13438        }
13439
13440        @Override
13441        protected void dumpFilter(PrintWriter out, String prefix,
13442                PackageParser.ActivityIntentInfo filter) {
13443            out.print(prefix); out.print(
13444                    Integer.toHexString(System.identityHashCode(filter.activity)));
13445                    out.print(' ');
13446                    filter.activity.printComponentShortName(out);
13447                    out.print(" filter ");
13448                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13449        }
13450
13451        @Override
13452        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
13453            return filter.activity;
13454        }
13455
13456        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13457            PackageParser.Activity activity = (PackageParser.Activity)label;
13458            out.print(prefix); out.print(
13459                    Integer.toHexString(System.identityHashCode(activity)));
13460                    out.print(' ');
13461                    activity.printComponentShortName(out);
13462            if (count > 1) {
13463                out.print(" ("); out.print(count); out.print(" filters)");
13464            }
13465            out.println();
13466        }
13467
13468        // Keys are String (activity class name), values are Activity.
13469        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
13470                = new ArrayMap<ComponentName, PackageParser.Activity>();
13471        private int mFlags;
13472    }
13473
13474    private final class ServiceIntentResolver
13475            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
13476        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13477                boolean defaultOnly, int userId) {
13478            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13479            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13480        }
13481
13482        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13483                int userId) {
13484            if (!sUserManager.exists(userId)) return null;
13485            mFlags = flags;
13486            return super.queryIntent(intent, resolvedType,
13487                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13488                    userId);
13489        }
13490
13491        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13492                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
13493            if (!sUserManager.exists(userId)) return null;
13494            if (packageServices == null) {
13495                return null;
13496            }
13497            mFlags = flags;
13498            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
13499            final int N = packageServices.size();
13500            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
13501                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
13502
13503            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
13504            for (int i = 0; i < N; ++i) {
13505                intentFilters = packageServices.get(i).intents;
13506                if (intentFilters != null && intentFilters.size() > 0) {
13507                    PackageParser.ServiceIntentInfo[] array =
13508                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
13509                    intentFilters.toArray(array);
13510                    listCut.add(array);
13511                }
13512            }
13513            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13514        }
13515
13516        public final void addService(PackageParser.Service s) {
13517            mServices.put(s.getComponentName(), s);
13518            if (DEBUG_SHOW_INFO) {
13519                Log.v(TAG, "  "
13520                        + (s.info.nonLocalizedLabel != null
13521                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13522                Log.v(TAG, "    Class=" + s.info.name);
13523            }
13524            final int NI = s.intents.size();
13525            int j;
13526            for (j=0; j<NI; j++) {
13527                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13528                if (DEBUG_SHOW_INFO) {
13529                    Log.v(TAG, "    IntentFilter:");
13530                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13531                }
13532                if (!intent.debugCheck()) {
13533                    Log.w(TAG, "==> For Service " + s.info.name);
13534                }
13535                addFilter(intent);
13536            }
13537        }
13538
13539        public final void removeService(PackageParser.Service s) {
13540            mServices.remove(s.getComponentName());
13541            if (DEBUG_SHOW_INFO) {
13542                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
13543                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13544                Log.v(TAG, "    Class=" + s.info.name);
13545            }
13546            final int NI = s.intents.size();
13547            int j;
13548            for (j=0; j<NI; j++) {
13549                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13550                if (DEBUG_SHOW_INFO) {
13551                    Log.v(TAG, "    IntentFilter:");
13552                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13553                }
13554                removeFilter(intent);
13555            }
13556        }
13557
13558        @Override
13559        protected boolean allowFilterResult(
13560                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
13561            ServiceInfo filterSi = filter.service.info;
13562            for (int i=dest.size()-1; i>=0; i--) {
13563                ServiceInfo destAi = dest.get(i).serviceInfo;
13564                if (destAi.name == filterSi.name
13565                        && destAi.packageName == filterSi.packageName) {
13566                    return false;
13567                }
13568            }
13569            return true;
13570        }
13571
13572        @Override
13573        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
13574            return new PackageParser.ServiceIntentInfo[size];
13575        }
13576
13577        @Override
13578        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
13579            if (!sUserManager.exists(userId)) return true;
13580            PackageParser.Package p = filter.service.owner;
13581            if (p != null) {
13582                PackageSetting ps = (PackageSetting)p.mExtras;
13583                if (ps != null) {
13584                    // System apps are never considered stopped for purposes of
13585                    // filtering, because there may be no way for the user to
13586                    // actually re-launch them.
13587                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13588                            && ps.getStopped(userId);
13589                }
13590            }
13591            return false;
13592        }
13593
13594        @Override
13595        protected boolean isPackageForFilter(String packageName,
13596                PackageParser.ServiceIntentInfo info) {
13597            return packageName.equals(info.service.owner.packageName);
13598        }
13599
13600        @Override
13601        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
13602                int match, int userId) {
13603            if (!sUserManager.exists(userId)) return null;
13604            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
13605            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
13606                return null;
13607            }
13608            final PackageParser.Service service = info.service;
13609            PackageSetting ps = (PackageSetting) service.owner.mExtras;
13610            if (ps == null) {
13611                return null;
13612            }
13613            final PackageUserState userState = ps.readUserState(userId);
13614            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
13615                    userState, userId);
13616            if (si == null) {
13617                return null;
13618            }
13619            final boolean matchVisibleToInstantApp =
13620                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13621            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13622            // throw out filters that aren't visible to ephemeral apps
13623            if (matchVisibleToInstantApp
13624                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13625                return null;
13626            }
13627            // throw out ephemeral filters if we're not explicitly requesting them
13628            if (!isInstantApp && userState.instantApp) {
13629                return null;
13630            }
13631            // throw out instant app filters if updates are available; will trigger
13632            // instant app resolution
13633            if (userState.instantApp && ps.isUpdateAvailable()) {
13634                return null;
13635            }
13636            final ResolveInfo res = new ResolveInfo();
13637            res.serviceInfo = si;
13638            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13639                res.filter = filter;
13640            }
13641            res.priority = info.getPriority();
13642            res.preferredOrder = service.owner.mPreferredOrder;
13643            res.match = match;
13644            res.isDefault = info.hasDefault;
13645            res.labelRes = info.labelRes;
13646            res.nonLocalizedLabel = info.nonLocalizedLabel;
13647            res.icon = info.icon;
13648            res.system = res.serviceInfo.applicationInfo.isSystemApp();
13649            return res;
13650        }
13651
13652        @Override
13653        protected void sortResults(List<ResolveInfo> results) {
13654            Collections.sort(results, mResolvePrioritySorter);
13655        }
13656
13657        @Override
13658        protected void dumpFilter(PrintWriter out, String prefix,
13659                PackageParser.ServiceIntentInfo filter) {
13660            out.print(prefix); out.print(
13661                    Integer.toHexString(System.identityHashCode(filter.service)));
13662                    out.print(' ');
13663                    filter.service.printComponentShortName(out);
13664                    out.print(" filter ");
13665                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13666        }
13667
13668        @Override
13669        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
13670            return filter.service;
13671        }
13672
13673        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13674            PackageParser.Service service = (PackageParser.Service)label;
13675            out.print(prefix); out.print(
13676                    Integer.toHexString(System.identityHashCode(service)));
13677                    out.print(' ');
13678                    service.printComponentShortName(out);
13679            if (count > 1) {
13680                out.print(" ("); out.print(count); out.print(" filters)");
13681            }
13682            out.println();
13683        }
13684
13685//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
13686//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
13687//            final List<ResolveInfo> retList = Lists.newArrayList();
13688//            while (i.hasNext()) {
13689//                final ResolveInfo resolveInfo = (ResolveInfo) i;
13690//                if (isEnabledLP(resolveInfo.serviceInfo)) {
13691//                    retList.add(resolveInfo);
13692//                }
13693//            }
13694//            return retList;
13695//        }
13696
13697        // Keys are String (activity class name), values are Activity.
13698        private final ArrayMap<ComponentName, PackageParser.Service> mServices
13699                = new ArrayMap<ComponentName, PackageParser.Service>();
13700        private int mFlags;
13701    }
13702
13703    private final class ProviderIntentResolver
13704            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
13705        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13706                boolean defaultOnly, int userId) {
13707            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13708            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13709        }
13710
13711        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13712                int userId) {
13713            if (!sUserManager.exists(userId))
13714                return null;
13715            mFlags = flags;
13716            return super.queryIntent(intent, resolvedType,
13717                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13718                    userId);
13719        }
13720
13721        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13722                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
13723            if (!sUserManager.exists(userId))
13724                return null;
13725            if (packageProviders == null) {
13726                return null;
13727            }
13728            mFlags = flags;
13729            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
13730            final int N = packageProviders.size();
13731            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
13732                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
13733
13734            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
13735            for (int i = 0; i < N; ++i) {
13736                intentFilters = packageProviders.get(i).intents;
13737                if (intentFilters != null && intentFilters.size() > 0) {
13738                    PackageParser.ProviderIntentInfo[] array =
13739                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
13740                    intentFilters.toArray(array);
13741                    listCut.add(array);
13742                }
13743            }
13744            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13745        }
13746
13747        public final void addProvider(PackageParser.Provider p) {
13748            if (mProviders.containsKey(p.getComponentName())) {
13749                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
13750                return;
13751            }
13752
13753            mProviders.put(p.getComponentName(), p);
13754            if (DEBUG_SHOW_INFO) {
13755                Log.v(TAG, "  "
13756                        + (p.info.nonLocalizedLabel != null
13757                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
13758                Log.v(TAG, "    Class=" + p.info.name);
13759            }
13760            final int NI = p.intents.size();
13761            int j;
13762            for (j = 0; j < NI; j++) {
13763                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13764                if (DEBUG_SHOW_INFO) {
13765                    Log.v(TAG, "    IntentFilter:");
13766                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13767                }
13768                if (!intent.debugCheck()) {
13769                    Log.w(TAG, "==> For Provider " + p.info.name);
13770                }
13771                addFilter(intent);
13772            }
13773        }
13774
13775        public final void removeProvider(PackageParser.Provider p) {
13776            mProviders.remove(p.getComponentName());
13777            if (DEBUG_SHOW_INFO) {
13778                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
13779                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
13780                Log.v(TAG, "    Class=" + p.info.name);
13781            }
13782            final int NI = p.intents.size();
13783            int j;
13784            for (j = 0; j < NI; j++) {
13785                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13786                if (DEBUG_SHOW_INFO) {
13787                    Log.v(TAG, "    IntentFilter:");
13788                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13789                }
13790                removeFilter(intent);
13791            }
13792        }
13793
13794        @Override
13795        protected boolean allowFilterResult(
13796                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
13797            ProviderInfo filterPi = filter.provider.info;
13798            for (int i = dest.size() - 1; i >= 0; i--) {
13799                ProviderInfo destPi = dest.get(i).providerInfo;
13800                if (destPi.name == filterPi.name
13801                        && destPi.packageName == filterPi.packageName) {
13802                    return false;
13803                }
13804            }
13805            return true;
13806        }
13807
13808        @Override
13809        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
13810            return new PackageParser.ProviderIntentInfo[size];
13811        }
13812
13813        @Override
13814        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
13815            if (!sUserManager.exists(userId))
13816                return true;
13817            PackageParser.Package p = filter.provider.owner;
13818            if (p != null) {
13819                PackageSetting ps = (PackageSetting) p.mExtras;
13820                if (ps != null) {
13821                    // System apps are never considered stopped for purposes of
13822                    // filtering, because there may be no way for the user to
13823                    // actually re-launch them.
13824                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13825                            && ps.getStopped(userId);
13826                }
13827            }
13828            return false;
13829        }
13830
13831        @Override
13832        protected boolean isPackageForFilter(String packageName,
13833                PackageParser.ProviderIntentInfo info) {
13834            return packageName.equals(info.provider.owner.packageName);
13835        }
13836
13837        @Override
13838        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
13839                int match, int userId) {
13840            if (!sUserManager.exists(userId))
13841                return null;
13842            final PackageParser.ProviderIntentInfo info = filter;
13843            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
13844                return null;
13845            }
13846            final PackageParser.Provider provider = info.provider;
13847            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
13848            if (ps == null) {
13849                return null;
13850            }
13851            final PackageUserState userState = ps.readUserState(userId);
13852            final boolean matchVisibleToInstantApp =
13853                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13854            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13855            // throw out filters that aren't visible to instant applications
13856            if (matchVisibleToInstantApp
13857                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13858                return null;
13859            }
13860            // throw out instant application filters if we're not explicitly requesting them
13861            if (!isInstantApp && userState.instantApp) {
13862                return null;
13863            }
13864            // throw out instant application filters if updates are available; will trigger
13865            // instant application resolution
13866            if (userState.instantApp && ps.isUpdateAvailable()) {
13867                return null;
13868            }
13869            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
13870                    userState, userId);
13871            if (pi == null) {
13872                return null;
13873            }
13874            final ResolveInfo res = new ResolveInfo();
13875            res.providerInfo = pi;
13876            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
13877                res.filter = filter;
13878            }
13879            res.priority = info.getPriority();
13880            res.preferredOrder = provider.owner.mPreferredOrder;
13881            res.match = match;
13882            res.isDefault = info.hasDefault;
13883            res.labelRes = info.labelRes;
13884            res.nonLocalizedLabel = info.nonLocalizedLabel;
13885            res.icon = info.icon;
13886            res.system = res.providerInfo.applicationInfo.isSystemApp();
13887            return res;
13888        }
13889
13890        @Override
13891        protected void sortResults(List<ResolveInfo> results) {
13892            Collections.sort(results, mResolvePrioritySorter);
13893        }
13894
13895        @Override
13896        protected void dumpFilter(PrintWriter out, String prefix,
13897                PackageParser.ProviderIntentInfo filter) {
13898            out.print(prefix);
13899            out.print(
13900                    Integer.toHexString(System.identityHashCode(filter.provider)));
13901            out.print(' ');
13902            filter.provider.printComponentShortName(out);
13903            out.print(" filter ");
13904            out.println(Integer.toHexString(System.identityHashCode(filter)));
13905        }
13906
13907        @Override
13908        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
13909            return filter.provider;
13910        }
13911
13912        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13913            PackageParser.Provider provider = (PackageParser.Provider)label;
13914            out.print(prefix); out.print(
13915                    Integer.toHexString(System.identityHashCode(provider)));
13916                    out.print(' ');
13917                    provider.printComponentShortName(out);
13918            if (count > 1) {
13919                out.print(" ("); out.print(count); out.print(" filters)");
13920            }
13921            out.println();
13922        }
13923
13924        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
13925                = new ArrayMap<ComponentName, PackageParser.Provider>();
13926        private int mFlags;
13927    }
13928
13929    static final class EphemeralIntentResolver
13930            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
13931        /**
13932         * The result that has the highest defined order. Ordering applies on a
13933         * per-package basis. Mapping is from package name to Pair of order and
13934         * EphemeralResolveInfo.
13935         * <p>
13936         * NOTE: This is implemented as a field variable for convenience and efficiency.
13937         * By having a field variable, we're able to track filter ordering as soon as
13938         * a non-zero order is defined. Otherwise, multiple loops across the result set
13939         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
13940         * this needs to be contained entirely within {@link #filterResults}.
13941         */
13942        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
13943
13944        @Override
13945        protected AuxiliaryResolveInfo[] newArray(int size) {
13946            return new AuxiliaryResolveInfo[size];
13947        }
13948
13949        @Override
13950        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
13951            return true;
13952        }
13953
13954        @Override
13955        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
13956                int userId) {
13957            if (!sUserManager.exists(userId)) {
13958                return null;
13959            }
13960            final String packageName = responseObj.resolveInfo.getPackageName();
13961            final Integer order = responseObj.getOrder();
13962            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
13963                    mOrderResult.get(packageName);
13964            // ordering is enabled and this item's order isn't high enough
13965            if (lastOrderResult != null && lastOrderResult.first >= order) {
13966                return null;
13967            }
13968            final InstantAppResolveInfo res = responseObj.resolveInfo;
13969            if (order > 0) {
13970                // non-zero order, enable ordering
13971                mOrderResult.put(packageName, new Pair<>(order, res));
13972            }
13973            return responseObj;
13974        }
13975
13976        @Override
13977        protected void filterResults(List<AuxiliaryResolveInfo> results) {
13978            // only do work if ordering is enabled [most of the time it won't be]
13979            if (mOrderResult.size() == 0) {
13980                return;
13981            }
13982            int resultSize = results.size();
13983            for (int i = 0; i < resultSize; i++) {
13984                final InstantAppResolveInfo info = results.get(i).resolveInfo;
13985                final String packageName = info.getPackageName();
13986                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
13987                if (savedInfo == null) {
13988                    // package doesn't having ordering
13989                    continue;
13990                }
13991                if (savedInfo.second == info) {
13992                    // circled back to the highest ordered item; remove from order list
13993                    mOrderResult.remove(savedInfo);
13994                    if (mOrderResult.size() == 0) {
13995                        // no more ordered items
13996                        break;
13997                    }
13998                    continue;
13999                }
14000                // item has a worse order, remove it from the result list
14001                results.remove(i);
14002                resultSize--;
14003                i--;
14004            }
14005        }
14006    }
14007
14008    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
14009            new Comparator<ResolveInfo>() {
14010        public int compare(ResolveInfo r1, ResolveInfo r2) {
14011            int v1 = r1.priority;
14012            int v2 = r2.priority;
14013            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
14014            if (v1 != v2) {
14015                return (v1 > v2) ? -1 : 1;
14016            }
14017            v1 = r1.preferredOrder;
14018            v2 = r2.preferredOrder;
14019            if (v1 != v2) {
14020                return (v1 > v2) ? -1 : 1;
14021            }
14022            if (r1.isDefault != r2.isDefault) {
14023                return r1.isDefault ? -1 : 1;
14024            }
14025            v1 = r1.match;
14026            v2 = r2.match;
14027            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
14028            if (v1 != v2) {
14029                return (v1 > v2) ? -1 : 1;
14030            }
14031            if (r1.system != r2.system) {
14032                return r1.system ? -1 : 1;
14033            }
14034            if (r1.activityInfo != null) {
14035                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
14036            }
14037            if (r1.serviceInfo != null) {
14038                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
14039            }
14040            if (r1.providerInfo != null) {
14041                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
14042            }
14043            return 0;
14044        }
14045    };
14046
14047    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
14048            new Comparator<ProviderInfo>() {
14049        public int compare(ProviderInfo p1, ProviderInfo p2) {
14050            final int v1 = p1.initOrder;
14051            final int v2 = p2.initOrder;
14052            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
14053        }
14054    };
14055
14056    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
14057            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
14058            final int[] userIds) {
14059        mHandler.post(new Runnable() {
14060            @Override
14061            public void run() {
14062                try {
14063                    final IActivityManager am = ActivityManager.getService();
14064                    if (am == null) return;
14065                    final int[] resolvedUserIds;
14066                    if (userIds == null) {
14067                        resolvedUserIds = am.getRunningUserIds();
14068                    } else {
14069                        resolvedUserIds = userIds;
14070                    }
14071                    for (int id : resolvedUserIds) {
14072                        final Intent intent = new Intent(action,
14073                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
14074                        if (extras != null) {
14075                            intent.putExtras(extras);
14076                        }
14077                        if (targetPkg != null) {
14078                            intent.setPackage(targetPkg);
14079                        }
14080                        // Modify the UID when posting to other users
14081                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
14082                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
14083                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
14084                            intent.putExtra(Intent.EXTRA_UID, uid);
14085                        }
14086                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
14087                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
14088                        if (DEBUG_BROADCASTS) {
14089                            RuntimeException here = new RuntimeException("here");
14090                            here.fillInStackTrace();
14091                            Slog.d(TAG, "Sending to user " + id + ": "
14092                                    + intent.toShortString(false, true, false, false)
14093                                    + " " + intent.getExtras(), here);
14094                        }
14095                        am.broadcastIntent(null, intent, null, finishedReceiver,
14096                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
14097                                null, finishedReceiver != null, false, id);
14098                    }
14099                } catch (RemoteException ex) {
14100                }
14101            }
14102        });
14103    }
14104
14105    /**
14106     * Check if the external storage media is available. This is true if there
14107     * is a mounted external storage medium or if the external storage is
14108     * emulated.
14109     */
14110    private boolean isExternalMediaAvailable() {
14111        return mMediaMounted || Environment.isExternalStorageEmulated();
14112    }
14113
14114    @Override
14115    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
14116        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14117            return null;
14118        }
14119        // writer
14120        synchronized (mPackages) {
14121            if (!isExternalMediaAvailable()) {
14122                // If the external storage is no longer mounted at this point,
14123                // the caller may not have been able to delete all of this
14124                // packages files and can not delete any more.  Bail.
14125                return null;
14126            }
14127            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
14128            if (lastPackage != null) {
14129                pkgs.remove(lastPackage);
14130            }
14131            if (pkgs.size() > 0) {
14132                return pkgs.get(0);
14133            }
14134        }
14135        return null;
14136    }
14137
14138    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
14139        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
14140                userId, andCode ? 1 : 0, packageName);
14141        if (mSystemReady) {
14142            msg.sendToTarget();
14143        } else {
14144            if (mPostSystemReadyMessages == null) {
14145                mPostSystemReadyMessages = new ArrayList<>();
14146            }
14147            mPostSystemReadyMessages.add(msg);
14148        }
14149    }
14150
14151    void startCleaningPackages() {
14152        // reader
14153        if (!isExternalMediaAvailable()) {
14154            return;
14155        }
14156        synchronized (mPackages) {
14157            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
14158                return;
14159            }
14160        }
14161        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
14162        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
14163        IActivityManager am = ActivityManager.getService();
14164        if (am != null) {
14165            int dcsUid = -1;
14166            synchronized (mPackages) {
14167                if (!mDefaultContainerWhitelisted) {
14168                    mDefaultContainerWhitelisted = true;
14169                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
14170                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
14171                }
14172            }
14173            try {
14174                if (dcsUid > 0) {
14175                    am.backgroundWhitelistUid(dcsUid);
14176                }
14177                am.startService(null, intent, null, false, mContext.getOpPackageName(),
14178                        UserHandle.USER_SYSTEM);
14179            } catch (RemoteException e) {
14180            }
14181        }
14182    }
14183
14184    @Override
14185    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
14186            int installFlags, String installerPackageName, int userId) {
14187        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
14188
14189        final int callingUid = Binder.getCallingUid();
14190        enforceCrossUserPermission(callingUid, userId,
14191                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
14192
14193        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14194            try {
14195                if (observer != null) {
14196                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
14197                }
14198            } catch (RemoteException re) {
14199            }
14200            return;
14201        }
14202
14203        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
14204            installFlags |= PackageManager.INSTALL_FROM_ADB;
14205
14206        } else {
14207            // Caller holds INSTALL_PACKAGES permission, so we're less strict
14208            // about installerPackageName.
14209
14210            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
14211            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
14212        }
14213
14214        UserHandle user;
14215        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
14216            user = UserHandle.ALL;
14217        } else {
14218            user = new UserHandle(userId);
14219        }
14220
14221        // Only system components can circumvent runtime permissions when installing.
14222        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
14223                && mContext.checkCallingOrSelfPermission(Manifest.permission
14224                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
14225            throw new SecurityException("You need the "
14226                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
14227                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
14228        }
14229
14230        if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
14231                || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
14232            throw new IllegalArgumentException(
14233                    "New installs into ASEC containers no longer supported");
14234        }
14235
14236        final File originFile = new File(originPath);
14237        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
14238
14239        final Message msg = mHandler.obtainMessage(INIT_COPY);
14240        final VerificationInfo verificationInfo = new VerificationInfo(
14241                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
14242        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
14243                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
14244                null /*packageAbiOverride*/, null /*grantedPermissions*/,
14245                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
14246        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
14247        msg.obj = params;
14248
14249        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
14250                System.identityHashCode(msg.obj));
14251        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14252                System.identityHashCode(msg.obj));
14253
14254        mHandler.sendMessage(msg);
14255    }
14256
14257
14258    /**
14259     * Ensure that the install reason matches what we know about the package installer (e.g. whether
14260     * it is acting on behalf on an enterprise or the user).
14261     *
14262     * Note that the ordering of the conditionals in this method is important. The checks we perform
14263     * are as follows, in this order:
14264     *
14265     * 1) If the install is being performed by a system app, we can trust the app to have set the
14266     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
14267     *    what it is.
14268     * 2) If the install is being performed by a device or profile owner app, the install reason
14269     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
14270     *    set the install reason correctly. If the app targets an older SDK version where install
14271     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
14272     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
14273     * 3) In all other cases, the install is being performed by a regular app that is neither part
14274     *    of the system nor a device or profile owner. We have no reason to believe that this app is
14275     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
14276     *    set to enterprise policy and if so, change it to unknown instead.
14277     */
14278    private int fixUpInstallReason(String installerPackageName, int installerUid,
14279            int installReason) {
14280        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
14281                == PERMISSION_GRANTED) {
14282            // If the install is being performed by a system app, we trust that app to have set the
14283            // install reason correctly.
14284            return installReason;
14285        }
14286
14287        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
14288            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
14289        if (dpm != null) {
14290            ComponentName owner = null;
14291            try {
14292                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
14293                if (owner == null) {
14294                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
14295                }
14296            } catch (RemoteException e) {
14297            }
14298            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
14299                // If the install is being performed by a device or profile owner, the install
14300                // reason should be enterprise policy.
14301                return PackageManager.INSTALL_REASON_POLICY;
14302            }
14303        }
14304
14305        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
14306            // If the install is being performed by a regular app (i.e. neither system app nor
14307            // device or profile owner), we have no reason to believe that the app is acting on
14308            // behalf of an enterprise. If the app set the install reason to enterprise policy,
14309            // change it to unknown instead.
14310            return PackageManager.INSTALL_REASON_UNKNOWN;
14311        }
14312
14313        // If the install is being performed by a regular app and the install reason was set to any
14314        // value but enterprise policy, leave the install reason unchanged.
14315        return installReason;
14316    }
14317
14318    void installStage(String packageName, File stagedDir, String stagedCid,
14319            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
14320            String installerPackageName, int installerUid, UserHandle user,
14321            Certificate[][] certificates) {
14322        if (DEBUG_EPHEMERAL) {
14323            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14324                Slog.d(TAG, "Ephemeral install of " + packageName);
14325            }
14326        }
14327        final VerificationInfo verificationInfo = new VerificationInfo(
14328                sessionParams.originatingUri, sessionParams.referrerUri,
14329                sessionParams.originatingUid, installerUid);
14330
14331        final OriginInfo origin;
14332        if (stagedDir != null) {
14333            origin = OriginInfo.fromStagedFile(stagedDir);
14334        } else {
14335            origin = OriginInfo.fromStagedContainer(stagedCid);
14336        }
14337
14338        final Message msg = mHandler.obtainMessage(INIT_COPY);
14339        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
14340                sessionParams.installReason);
14341        final InstallParams params = new InstallParams(origin, null, observer,
14342                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
14343                verificationInfo, user, sessionParams.abiOverride,
14344                sessionParams.grantedRuntimePermissions, certificates, installReason);
14345        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
14346        msg.obj = params;
14347
14348        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
14349                System.identityHashCode(msg.obj));
14350        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14351                System.identityHashCode(msg.obj));
14352
14353        mHandler.sendMessage(msg);
14354    }
14355
14356    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
14357            int userId) {
14358        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
14359        sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId);
14360
14361        // Send a session commit broadcast
14362        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
14363        info.installReason = pkgSetting.getInstallReason(userId);
14364        info.appPackageName = packageName;
14365        sendSessionCommitBroadcast(info, userId);
14366    }
14367
14368    public void sendPackageAddedForNewUsers(String packageName, boolean isSystem, int appId, int... userIds) {
14369        if (ArrayUtils.isEmpty(userIds)) {
14370            return;
14371        }
14372        Bundle extras = new Bundle(1);
14373        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
14374        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
14375
14376        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
14377                packageName, extras, 0, null, null, userIds);
14378        if (isSystem) {
14379            mHandler.post(() -> {
14380                        for (int userId : userIds) {
14381                            sendBootCompletedBroadcastToSystemApp(packageName, userId);
14382                        }
14383                    }
14384            );
14385        }
14386    }
14387
14388    /**
14389     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
14390     * automatically without needing an explicit launch.
14391     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
14392     */
14393    private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) {
14394        // If user is not running, the app didn't miss any broadcast
14395        if (!mUserManagerInternal.isUserRunning(userId)) {
14396            return;
14397        }
14398        final IActivityManager am = ActivityManager.getService();
14399        try {
14400            // Deliver LOCKED_BOOT_COMPLETED first
14401            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
14402                    .setPackage(packageName);
14403            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
14404            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
14405                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14406
14407            // Deliver BOOT_COMPLETED only if user is unlocked
14408            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
14409                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
14410                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
14411                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14412            }
14413        } catch (RemoteException e) {
14414            throw e.rethrowFromSystemServer();
14415        }
14416    }
14417
14418    @Override
14419    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
14420            int userId) {
14421        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14422        PackageSetting pkgSetting;
14423        final int callingUid = Binder.getCallingUid();
14424        enforceCrossUserPermission(callingUid, userId,
14425                true /* requireFullPermission */, true /* checkShell */,
14426                "setApplicationHiddenSetting for user " + userId);
14427
14428        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
14429            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
14430            return false;
14431        }
14432
14433        long callingId = Binder.clearCallingIdentity();
14434        try {
14435            boolean sendAdded = false;
14436            boolean sendRemoved = false;
14437            // writer
14438            synchronized (mPackages) {
14439                pkgSetting = mSettings.mPackages.get(packageName);
14440                if (pkgSetting == null) {
14441                    return false;
14442                }
14443                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14444                    return false;
14445                }
14446                // Do not allow "android" is being disabled
14447                if ("android".equals(packageName)) {
14448                    Slog.w(TAG, "Cannot hide package: android");
14449                    return false;
14450                }
14451                // Cannot hide static shared libs as they are considered
14452                // a part of the using app (emulating static linking). Also
14453                // static libs are installed always on internal storage.
14454                PackageParser.Package pkg = mPackages.get(packageName);
14455                if (pkg != null && pkg.staticSharedLibName != null) {
14456                    Slog.w(TAG, "Cannot hide package: " + packageName
14457                            + " providing static shared library: "
14458                            + pkg.staticSharedLibName);
14459                    return false;
14460                }
14461                // Only allow protected packages to hide themselves.
14462                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
14463                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14464                    Slog.w(TAG, "Not hiding protected package: " + packageName);
14465                    return false;
14466                }
14467
14468                if (pkgSetting.getHidden(userId) != hidden) {
14469                    pkgSetting.setHidden(hidden, userId);
14470                    mSettings.writePackageRestrictionsLPr(userId);
14471                    if (hidden) {
14472                        sendRemoved = true;
14473                    } else {
14474                        sendAdded = true;
14475                    }
14476                }
14477            }
14478            if (sendAdded) {
14479                sendPackageAddedForUser(packageName, pkgSetting, userId);
14480                return true;
14481            }
14482            if (sendRemoved) {
14483                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
14484                        "hiding pkg");
14485                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
14486                return true;
14487            }
14488        } finally {
14489            Binder.restoreCallingIdentity(callingId);
14490        }
14491        return false;
14492    }
14493
14494    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
14495            int userId) {
14496        final PackageRemovedInfo info = new PackageRemovedInfo(this);
14497        info.removedPackage = packageName;
14498        info.installerPackageName = pkgSetting.installerPackageName;
14499        info.removedUsers = new int[] {userId};
14500        info.broadcastUsers = new int[] {userId};
14501        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
14502        info.sendPackageRemovedBroadcasts(true /*killApp*/);
14503    }
14504
14505    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
14506        if (pkgList.length > 0) {
14507            Bundle extras = new Bundle(1);
14508            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
14509
14510            sendPackageBroadcast(
14511                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
14512                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
14513                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
14514                    new int[] {userId});
14515        }
14516    }
14517
14518    /**
14519     * Returns true if application is not found or there was an error. Otherwise it returns
14520     * the hidden state of the package for the given user.
14521     */
14522    @Override
14523    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
14524        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14525        final int callingUid = Binder.getCallingUid();
14526        enforceCrossUserPermission(callingUid, userId,
14527                true /* requireFullPermission */, false /* checkShell */,
14528                "getApplicationHidden for user " + userId);
14529        PackageSetting ps;
14530        long callingId = Binder.clearCallingIdentity();
14531        try {
14532            // writer
14533            synchronized (mPackages) {
14534                ps = mSettings.mPackages.get(packageName);
14535                if (ps == null) {
14536                    return true;
14537                }
14538                if (filterAppAccessLPr(ps, callingUid, userId)) {
14539                    return true;
14540                }
14541                return ps.getHidden(userId);
14542            }
14543        } finally {
14544            Binder.restoreCallingIdentity(callingId);
14545        }
14546    }
14547
14548    /**
14549     * @hide
14550     */
14551    @Override
14552    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
14553            int installReason) {
14554        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
14555                null);
14556        PackageSetting pkgSetting;
14557        final int callingUid = Binder.getCallingUid();
14558        enforceCrossUserPermission(callingUid, userId,
14559                true /* requireFullPermission */, true /* checkShell */,
14560                "installExistingPackage for user " + userId);
14561        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14562            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
14563        }
14564
14565        long callingId = Binder.clearCallingIdentity();
14566        try {
14567            boolean installed = false;
14568            final boolean instantApp =
14569                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14570            final boolean fullApp =
14571                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
14572
14573            // writer
14574            synchronized (mPackages) {
14575                pkgSetting = mSettings.mPackages.get(packageName);
14576                if (pkgSetting == null) {
14577                    return PackageManager.INSTALL_FAILED_INVALID_URI;
14578                }
14579                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
14580                    // only allow the existing package to be used if it's installed as a full
14581                    // application for at least one user
14582                    boolean installAllowed = false;
14583                    for (int checkUserId : sUserManager.getUserIds()) {
14584                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
14585                        if (installAllowed) {
14586                            break;
14587                        }
14588                    }
14589                    if (!installAllowed) {
14590                        return PackageManager.INSTALL_FAILED_INVALID_URI;
14591                    }
14592                }
14593                if (!pkgSetting.getInstalled(userId)) {
14594                    pkgSetting.setInstalled(true, userId);
14595                    pkgSetting.setHidden(false, userId);
14596                    pkgSetting.setInstallReason(installReason, userId);
14597                    mSettings.writePackageRestrictionsLPr(userId);
14598                    mSettings.writeKernelMappingLPr(pkgSetting);
14599                    installed = true;
14600                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14601                    // upgrade app from instant to full; we don't allow app downgrade
14602                    installed = true;
14603                }
14604                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
14605            }
14606
14607            if (installed) {
14608                if (pkgSetting.pkg != null) {
14609                    synchronized (mInstallLock) {
14610                        // We don't need to freeze for a brand new install
14611                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
14612                    }
14613                }
14614                sendPackageAddedForUser(packageName, pkgSetting, userId);
14615                synchronized (mPackages) {
14616                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
14617                }
14618            }
14619        } finally {
14620            Binder.restoreCallingIdentity(callingId);
14621        }
14622
14623        return PackageManager.INSTALL_SUCCEEDED;
14624    }
14625
14626    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
14627            boolean instantApp, boolean fullApp) {
14628        // no state specified; do nothing
14629        if (!instantApp && !fullApp) {
14630            return;
14631        }
14632        if (userId != UserHandle.USER_ALL) {
14633            if (instantApp && !pkgSetting.getInstantApp(userId)) {
14634                pkgSetting.setInstantApp(true /*instantApp*/, userId);
14635            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14636                pkgSetting.setInstantApp(false /*instantApp*/, userId);
14637            }
14638        } else {
14639            for (int currentUserId : sUserManager.getUserIds()) {
14640                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
14641                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
14642                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
14643                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
14644                }
14645            }
14646        }
14647    }
14648
14649    boolean isUserRestricted(int userId, String restrictionKey) {
14650        Bundle restrictions = sUserManager.getUserRestrictions(userId);
14651        if (restrictions.getBoolean(restrictionKey, false)) {
14652            Log.w(TAG, "User is restricted: " + restrictionKey);
14653            return true;
14654        }
14655        return false;
14656    }
14657
14658    @Override
14659    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
14660            int userId) {
14661        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14662        final int callingUid = Binder.getCallingUid();
14663        enforceCrossUserPermission(callingUid, userId,
14664                true /* requireFullPermission */, true /* checkShell */,
14665                "setPackagesSuspended for user " + userId);
14666
14667        if (ArrayUtils.isEmpty(packageNames)) {
14668            return packageNames;
14669        }
14670
14671        // List of package names for whom the suspended state has changed.
14672        List<String> changedPackages = new ArrayList<>(packageNames.length);
14673        // List of package names for whom the suspended state is not set as requested in this
14674        // method.
14675        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
14676        long callingId = Binder.clearCallingIdentity();
14677        try {
14678            for (int i = 0; i < packageNames.length; i++) {
14679                String packageName = packageNames[i];
14680                boolean changed = false;
14681                final int appId;
14682                synchronized (mPackages) {
14683                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
14684                    if (pkgSetting == null
14685                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14686                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
14687                                + "\". Skipping suspending/un-suspending.");
14688                        unactionedPackages.add(packageName);
14689                        continue;
14690                    }
14691                    appId = pkgSetting.appId;
14692                    if (pkgSetting.getSuspended(userId) != suspended) {
14693                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
14694                            unactionedPackages.add(packageName);
14695                            continue;
14696                        }
14697                        pkgSetting.setSuspended(suspended, userId);
14698                        mSettings.writePackageRestrictionsLPr(userId);
14699                        changed = true;
14700                        changedPackages.add(packageName);
14701                    }
14702                }
14703
14704                if (changed && suspended) {
14705                    killApplication(packageName, UserHandle.getUid(userId, appId),
14706                            "suspending package");
14707                }
14708            }
14709        } finally {
14710            Binder.restoreCallingIdentity(callingId);
14711        }
14712
14713        if (!changedPackages.isEmpty()) {
14714            sendPackagesSuspendedForUser(changedPackages.toArray(
14715                    new String[changedPackages.size()]), userId, suspended);
14716        }
14717
14718        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
14719    }
14720
14721    @Override
14722    public boolean isPackageSuspendedForUser(String packageName, int userId) {
14723        final int callingUid = Binder.getCallingUid();
14724        enforceCrossUserPermission(callingUid, userId,
14725                true /* requireFullPermission */, false /* checkShell */,
14726                "isPackageSuspendedForUser for user " + userId);
14727        synchronized (mPackages) {
14728            final PackageSetting ps = mSettings.mPackages.get(packageName);
14729            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
14730                throw new IllegalArgumentException("Unknown target package: " + packageName);
14731            }
14732            return ps.getSuspended(userId);
14733        }
14734    }
14735
14736    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
14737        if (isPackageDeviceAdmin(packageName, userId)) {
14738            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14739                    + "\": has an active device admin");
14740            return false;
14741        }
14742
14743        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
14744        if (packageName.equals(activeLauncherPackageName)) {
14745            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14746                    + "\": contains the active launcher");
14747            return false;
14748        }
14749
14750        if (packageName.equals(mRequiredInstallerPackage)) {
14751            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14752                    + "\": required for package installation");
14753            return false;
14754        }
14755
14756        if (packageName.equals(mRequiredUninstallerPackage)) {
14757            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14758                    + "\": required for package uninstallation");
14759            return false;
14760        }
14761
14762        if (packageName.equals(mRequiredVerifierPackage)) {
14763            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14764                    + "\": required for package verification");
14765            return false;
14766        }
14767
14768        if (packageName.equals(getDefaultDialerPackageName(userId))) {
14769            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14770                    + "\": is the default dialer");
14771            return false;
14772        }
14773
14774        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14775            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14776                    + "\": protected package");
14777            return false;
14778        }
14779
14780        // Cannot suspend static shared libs as they are considered
14781        // a part of the using app (emulating static linking). Also
14782        // static libs are installed always on internal storage.
14783        PackageParser.Package pkg = mPackages.get(packageName);
14784        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
14785            Slog.w(TAG, "Cannot suspend package: " + packageName
14786                    + " providing static shared library: "
14787                    + pkg.staticSharedLibName);
14788            return false;
14789        }
14790
14791        return true;
14792    }
14793
14794    private String getActiveLauncherPackageName(int userId) {
14795        Intent intent = new Intent(Intent.ACTION_MAIN);
14796        intent.addCategory(Intent.CATEGORY_HOME);
14797        ResolveInfo resolveInfo = resolveIntent(
14798                intent,
14799                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
14800                PackageManager.MATCH_DEFAULT_ONLY,
14801                userId);
14802
14803        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
14804    }
14805
14806    private String getDefaultDialerPackageName(int userId) {
14807        synchronized (mPackages) {
14808            return mSettings.getDefaultDialerPackageNameLPw(userId);
14809        }
14810    }
14811
14812    @Override
14813    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
14814        mContext.enforceCallingOrSelfPermission(
14815                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14816                "Only package verification agents can verify applications");
14817
14818        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14819        final PackageVerificationResponse response = new PackageVerificationResponse(
14820                verificationCode, Binder.getCallingUid());
14821        msg.arg1 = id;
14822        msg.obj = response;
14823        mHandler.sendMessage(msg);
14824    }
14825
14826    @Override
14827    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
14828            long millisecondsToDelay) {
14829        mContext.enforceCallingOrSelfPermission(
14830                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14831                "Only package verification agents can extend verification timeouts");
14832
14833        final PackageVerificationState state = mPendingVerification.get(id);
14834        final PackageVerificationResponse response = new PackageVerificationResponse(
14835                verificationCodeAtTimeout, Binder.getCallingUid());
14836
14837        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
14838            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
14839        }
14840        if (millisecondsToDelay < 0) {
14841            millisecondsToDelay = 0;
14842        }
14843        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
14844                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
14845            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
14846        }
14847
14848        if ((state != null) && !state.timeoutExtended()) {
14849            state.extendTimeout();
14850
14851            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14852            msg.arg1 = id;
14853            msg.obj = response;
14854            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
14855        }
14856    }
14857
14858    private void broadcastPackageVerified(int verificationId, Uri packageUri,
14859            int verificationCode, UserHandle user) {
14860        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
14861        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
14862        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14863        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14864        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
14865
14866        mContext.sendBroadcastAsUser(intent, user,
14867                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
14868    }
14869
14870    private ComponentName matchComponentForVerifier(String packageName,
14871            List<ResolveInfo> receivers) {
14872        ActivityInfo targetReceiver = null;
14873
14874        final int NR = receivers.size();
14875        for (int i = 0; i < NR; i++) {
14876            final ResolveInfo info = receivers.get(i);
14877            if (info.activityInfo == null) {
14878                continue;
14879            }
14880
14881            if (packageName.equals(info.activityInfo.packageName)) {
14882                targetReceiver = info.activityInfo;
14883                break;
14884            }
14885        }
14886
14887        if (targetReceiver == null) {
14888            return null;
14889        }
14890
14891        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
14892    }
14893
14894    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
14895            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
14896        if (pkgInfo.verifiers.length == 0) {
14897            return null;
14898        }
14899
14900        final int N = pkgInfo.verifiers.length;
14901        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
14902        for (int i = 0; i < N; i++) {
14903            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
14904
14905            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
14906                    receivers);
14907            if (comp == null) {
14908                continue;
14909            }
14910
14911            final int verifierUid = getUidForVerifier(verifierInfo);
14912            if (verifierUid == -1) {
14913                continue;
14914            }
14915
14916            if (DEBUG_VERIFY) {
14917                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
14918                        + " with the correct signature");
14919            }
14920            sufficientVerifiers.add(comp);
14921            verificationState.addSufficientVerifier(verifierUid);
14922        }
14923
14924        return sufficientVerifiers;
14925    }
14926
14927    private int getUidForVerifier(VerifierInfo verifierInfo) {
14928        synchronized (mPackages) {
14929            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
14930            if (pkg == null) {
14931                return -1;
14932            } else if (pkg.mSignatures.length != 1) {
14933                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14934                        + " has more than one signature; ignoring");
14935                return -1;
14936            }
14937
14938            /*
14939             * If the public key of the package's signature does not match
14940             * our expected public key, then this is a different package and
14941             * we should skip.
14942             */
14943
14944            final byte[] expectedPublicKey;
14945            try {
14946                final Signature verifierSig = pkg.mSignatures[0];
14947                final PublicKey publicKey = verifierSig.getPublicKey();
14948                expectedPublicKey = publicKey.getEncoded();
14949            } catch (CertificateException e) {
14950                return -1;
14951            }
14952
14953            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
14954
14955            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
14956                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14957                        + " does not have the expected public key; ignoring");
14958                return -1;
14959            }
14960
14961            return pkg.applicationInfo.uid;
14962        }
14963    }
14964
14965    @Override
14966    public void finishPackageInstall(int token, boolean didLaunch) {
14967        enforceSystemOrRoot("Only the system is allowed to finish installs");
14968
14969        if (DEBUG_INSTALL) {
14970            Slog.v(TAG, "BM finishing package install for " + token);
14971        }
14972        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14973
14974        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
14975        mHandler.sendMessage(msg);
14976    }
14977
14978    /**
14979     * Get the verification agent timeout.  Used for both the APK verifier and the
14980     * intent filter verifier.
14981     *
14982     * @return verification timeout in milliseconds
14983     */
14984    private long getVerificationTimeout() {
14985        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
14986                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
14987                DEFAULT_VERIFICATION_TIMEOUT);
14988    }
14989
14990    /**
14991     * Get the default verification agent response code.
14992     *
14993     * @return default verification response code
14994     */
14995    private int getDefaultVerificationResponse(UserHandle user) {
14996        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
14997            return PackageManager.VERIFICATION_REJECT;
14998        }
14999        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15000                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
15001                DEFAULT_VERIFICATION_RESPONSE);
15002    }
15003
15004    /**
15005     * Check whether or not package verification has been enabled.
15006     *
15007     * @return true if verification should be performed
15008     */
15009    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
15010        if (!DEFAULT_VERIFY_ENABLE) {
15011            return false;
15012        }
15013
15014        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
15015
15016        // Check if installing from ADB
15017        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
15018            // Do not run verification in a test harness environment
15019            if (ActivityManager.isRunningInTestHarness()) {
15020                return false;
15021            }
15022            if (ensureVerifyAppsEnabled) {
15023                return true;
15024            }
15025            // Check if the developer does not want package verification for ADB installs
15026            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15027                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
15028                return false;
15029            }
15030        } else {
15031            // only when not installed from ADB, skip verification for instant apps when
15032            // the installer and verifier are the same.
15033            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
15034                if (mInstantAppInstallerActivity != null
15035                        && mInstantAppInstallerActivity.packageName.equals(
15036                                mRequiredVerifierPackage)) {
15037                    try {
15038                        mContext.getSystemService(AppOpsManager.class)
15039                                .checkPackage(installerUid, mRequiredVerifierPackage);
15040                        if (DEBUG_VERIFY) {
15041                            Slog.i(TAG, "disable verification for instant app");
15042                        }
15043                        return false;
15044                    } catch (SecurityException ignore) { }
15045                }
15046            }
15047        }
15048
15049        if (ensureVerifyAppsEnabled) {
15050            return true;
15051        }
15052
15053        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15054                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
15055    }
15056
15057    @Override
15058    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
15059            throws RemoteException {
15060        mContext.enforceCallingOrSelfPermission(
15061                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
15062                "Only intentfilter verification agents can verify applications");
15063
15064        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
15065        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
15066                Binder.getCallingUid(), verificationCode, failedDomains);
15067        msg.arg1 = id;
15068        msg.obj = response;
15069        mHandler.sendMessage(msg);
15070    }
15071
15072    @Override
15073    public int getIntentVerificationStatus(String packageName, int userId) {
15074        final int callingUid = Binder.getCallingUid();
15075        if (UserHandle.getUserId(callingUid) != userId) {
15076            mContext.enforceCallingOrSelfPermission(
15077                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
15078                    "getIntentVerificationStatus" + userId);
15079        }
15080        if (getInstantAppPackageName(callingUid) != null) {
15081            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
15082        }
15083        synchronized (mPackages) {
15084            final PackageSetting ps = mSettings.mPackages.get(packageName);
15085            if (ps == null
15086                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15087                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
15088            }
15089            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
15090        }
15091    }
15092
15093    @Override
15094    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
15095        mContext.enforceCallingOrSelfPermission(
15096                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15097
15098        boolean result = false;
15099        synchronized (mPackages) {
15100            final PackageSetting ps = mSettings.mPackages.get(packageName);
15101            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15102                return false;
15103            }
15104            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
15105        }
15106        if (result) {
15107            scheduleWritePackageRestrictionsLocked(userId);
15108        }
15109        return result;
15110    }
15111
15112    @Override
15113    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
15114            String packageName) {
15115        final int callingUid = Binder.getCallingUid();
15116        if (getInstantAppPackageName(callingUid) != null) {
15117            return ParceledListSlice.emptyList();
15118        }
15119        synchronized (mPackages) {
15120            final PackageSetting ps = mSettings.mPackages.get(packageName);
15121            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15122                return ParceledListSlice.emptyList();
15123            }
15124            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
15125        }
15126    }
15127
15128    @Override
15129    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
15130        if (TextUtils.isEmpty(packageName)) {
15131            return ParceledListSlice.emptyList();
15132        }
15133        final int callingUid = Binder.getCallingUid();
15134        final int callingUserId = UserHandle.getUserId(callingUid);
15135        synchronized (mPackages) {
15136            PackageParser.Package pkg = mPackages.get(packageName);
15137            if (pkg == null || pkg.activities == null) {
15138                return ParceledListSlice.emptyList();
15139            }
15140            if (pkg.mExtras == null) {
15141                return ParceledListSlice.emptyList();
15142            }
15143            final PackageSetting ps = (PackageSetting) pkg.mExtras;
15144            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
15145                return ParceledListSlice.emptyList();
15146            }
15147            final int count = pkg.activities.size();
15148            ArrayList<IntentFilter> result = new ArrayList<>();
15149            for (int n=0; n<count; n++) {
15150                PackageParser.Activity activity = pkg.activities.get(n);
15151                if (activity.intents != null && activity.intents.size() > 0) {
15152                    result.addAll(activity.intents);
15153                }
15154            }
15155            return new ParceledListSlice<>(result);
15156        }
15157    }
15158
15159    @Override
15160    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
15161        mContext.enforceCallingOrSelfPermission(
15162                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15163        if (UserHandle.getCallingUserId() != userId) {
15164            mContext.enforceCallingOrSelfPermission(
15165                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
15166        }
15167
15168        synchronized (mPackages) {
15169            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
15170            if (packageName != null) {
15171                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
15172                        packageName, userId);
15173            }
15174            return result;
15175        }
15176    }
15177
15178    @Override
15179    public String getDefaultBrowserPackageName(int userId) {
15180        if (UserHandle.getCallingUserId() != userId) {
15181            mContext.enforceCallingOrSelfPermission(
15182                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
15183        }
15184        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15185            return null;
15186        }
15187        synchronized (mPackages) {
15188            return mSettings.getDefaultBrowserPackageNameLPw(userId);
15189        }
15190    }
15191
15192    /**
15193     * Get the "allow unknown sources" setting.
15194     *
15195     * @return the current "allow unknown sources" setting
15196     */
15197    private int getUnknownSourcesSettings() {
15198        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
15199                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
15200                -1);
15201    }
15202
15203    @Override
15204    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
15205        final int callingUid = Binder.getCallingUid();
15206        if (getInstantAppPackageName(callingUid) != null) {
15207            return;
15208        }
15209        // writer
15210        synchronized (mPackages) {
15211            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
15212            if (targetPackageSetting == null
15213                    || filterAppAccessLPr(
15214                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
15215                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
15216            }
15217
15218            PackageSetting installerPackageSetting;
15219            if (installerPackageName != null) {
15220                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
15221                if (installerPackageSetting == null) {
15222                    throw new IllegalArgumentException("Unknown installer package: "
15223                            + installerPackageName);
15224                }
15225            } else {
15226                installerPackageSetting = null;
15227            }
15228
15229            Signature[] callerSignature;
15230            Object obj = mSettings.getUserIdLPr(callingUid);
15231            if (obj != null) {
15232                if (obj instanceof SharedUserSetting) {
15233                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
15234                } else if (obj instanceof PackageSetting) {
15235                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
15236                } else {
15237                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
15238                }
15239            } else {
15240                throw new SecurityException("Unknown calling UID: " + callingUid);
15241            }
15242
15243            // Verify: can't set installerPackageName to a package that is
15244            // not signed with the same cert as the caller.
15245            if (installerPackageSetting != null) {
15246                if (compareSignatures(callerSignature,
15247                        installerPackageSetting.signatures.mSignatures)
15248                        != PackageManager.SIGNATURE_MATCH) {
15249                    throw new SecurityException(
15250                            "Caller does not have same cert as new installer package "
15251                            + installerPackageName);
15252                }
15253            }
15254
15255            // Verify: if target already has an installer package, it must
15256            // be signed with the same cert as the caller.
15257            if (targetPackageSetting.installerPackageName != null) {
15258                PackageSetting setting = mSettings.mPackages.get(
15259                        targetPackageSetting.installerPackageName);
15260                // If the currently set package isn't valid, then it's always
15261                // okay to change it.
15262                if (setting != null) {
15263                    if (compareSignatures(callerSignature,
15264                            setting.signatures.mSignatures)
15265                            != PackageManager.SIGNATURE_MATCH) {
15266                        throw new SecurityException(
15267                                "Caller does not have same cert as old installer package "
15268                                + targetPackageSetting.installerPackageName);
15269                    }
15270                }
15271            }
15272
15273            // Okay!
15274            targetPackageSetting.installerPackageName = installerPackageName;
15275            if (installerPackageName != null) {
15276                mSettings.mInstallerPackages.add(installerPackageName);
15277            }
15278            scheduleWriteSettingsLocked();
15279        }
15280    }
15281
15282    @Override
15283    public void setApplicationCategoryHint(String packageName, int categoryHint,
15284            String callerPackageName) {
15285        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15286            throw new SecurityException("Instant applications don't have access to this method");
15287        }
15288        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
15289                callerPackageName);
15290        synchronized (mPackages) {
15291            PackageSetting ps = mSettings.mPackages.get(packageName);
15292            if (ps == null) {
15293                throw new IllegalArgumentException("Unknown target package " + packageName);
15294            }
15295            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15296                throw new IllegalArgumentException("Unknown target package " + packageName);
15297            }
15298            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
15299                throw new IllegalArgumentException("Calling package " + callerPackageName
15300                        + " is not installer for " + packageName);
15301            }
15302
15303            if (ps.categoryHint != categoryHint) {
15304                ps.categoryHint = categoryHint;
15305                scheduleWriteSettingsLocked();
15306            }
15307        }
15308    }
15309
15310    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
15311        // Queue up an async operation since the package installation may take a little while.
15312        mHandler.post(new Runnable() {
15313            public void run() {
15314                mHandler.removeCallbacks(this);
15315                 // Result object to be returned
15316                PackageInstalledInfo res = new PackageInstalledInfo();
15317                res.setReturnCode(currentStatus);
15318                res.uid = -1;
15319                res.pkg = null;
15320                res.removedInfo = null;
15321                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15322                    args.doPreInstall(res.returnCode);
15323                    synchronized (mInstallLock) {
15324                        installPackageTracedLI(args, res);
15325                    }
15326                    args.doPostInstall(res.returnCode, res.uid);
15327                }
15328
15329                // A restore should be performed at this point if (a) the install
15330                // succeeded, (b) the operation is not an update, and (c) the new
15331                // package has not opted out of backup participation.
15332                final boolean update = res.removedInfo != null
15333                        && res.removedInfo.removedPackage != null;
15334                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
15335                boolean doRestore = !update
15336                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
15337
15338                // Set up the post-install work request bookkeeping.  This will be used
15339                // and cleaned up by the post-install event handling regardless of whether
15340                // there's a restore pass performed.  Token values are >= 1.
15341                int token;
15342                if (mNextInstallToken < 0) mNextInstallToken = 1;
15343                token = mNextInstallToken++;
15344
15345                PostInstallData data = new PostInstallData(args, res);
15346                mRunningInstalls.put(token, data);
15347                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
15348
15349                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
15350                    // Pass responsibility to the Backup Manager.  It will perform a
15351                    // restore if appropriate, then pass responsibility back to the
15352                    // Package Manager to run the post-install observer callbacks
15353                    // and broadcasts.
15354                    IBackupManager bm = IBackupManager.Stub.asInterface(
15355                            ServiceManager.getService(Context.BACKUP_SERVICE));
15356                    if (bm != null) {
15357                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
15358                                + " to BM for possible restore");
15359                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
15360                        try {
15361                            // TODO: http://b/22388012
15362                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
15363                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
15364                            } else {
15365                                doRestore = false;
15366                            }
15367                        } catch (RemoteException e) {
15368                            // can't happen; the backup manager is local
15369                        } catch (Exception e) {
15370                            Slog.e(TAG, "Exception trying to enqueue restore", e);
15371                            doRestore = false;
15372                        }
15373                    } else {
15374                        Slog.e(TAG, "Backup Manager not found!");
15375                        doRestore = false;
15376                    }
15377                }
15378
15379                if (!doRestore) {
15380                    // No restore possible, or the Backup Manager was mysteriously not
15381                    // available -- just fire the post-install work request directly.
15382                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
15383
15384                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
15385
15386                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
15387                    mHandler.sendMessage(msg);
15388                }
15389            }
15390        });
15391    }
15392
15393    /**
15394     * Callback from PackageSettings whenever an app is first transitioned out of the
15395     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
15396     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
15397     * here whether the app is the target of an ongoing install, and only send the
15398     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
15399     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
15400     * handling.
15401     */
15402    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
15403        // Serialize this with the rest of the install-process message chain.  In the
15404        // restore-at-install case, this Runnable will necessarily run before the
15405        // POST_INSTALL message is processed, so the contents of mRunningInstalls
15406        // are coherent.  In the non-restore case, the app has already completed install
15407        // and been launched through some other means, so it is not in a problematic
15408        // state for observers to see the FIRST_LAUNCH signal.
15409        mHandler.post(new Runnable() {
15410            @Override
15411            public void run() {
15412                for (int i = 0; i < mRunningInstalls.size(); i++) {
15413                    final PostInstallData data = mRunningInstalls.valueAt(i);
15414                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15415                        continue;
15416                    }
15417                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
15418                        // right package; but is it for the right user?
15419                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
15420                            if (userId == data.res.newUsers[uIndex]) {
15421                                if (DEBUG_BACKUP) {
15422                                    Slog.i(TAG, "Package " + pkgName
15423                                            + " being restored so deferring FIRST_LAUNCH");
15424                                }
15425                                return;
15426                            }
15427                        }
15428                    }
15429                }
15430                // didn't find it, so not being restored
15431                if (DEBUG_BACKUP) {
15432                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
15433                }
15434                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
15435            }
15436        });
15437    }
15438
15439    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
15440        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
15441                installerPkg, null, userIds);
15442    }
15443
15444    private abstract class HandlerParams {
15445        private static final int MAX_RETRIES = 4;
15446
15447        /**
15448         * Number of times startCopy() has been attempted and had a non-fatal
15449         * error.
15450         */
15451        private int mRetries = 0;
15452
15453        /** User handle for the user requesting the information or installation. */
15454        private final UserHandle mUser;
15455        String traceMethod;
15456        int traceCookie;
15457
15458        HandlerParams(UserHandle user) {
15459            mUser = user;
15460        }
15461
15462        UserHandle getUser() {
15463            return mUser;
15464        }
15465
15466        HandlerParams setTraceMethod(String traceMethod) {
15467            this.traceMethod = traceMethod;
15468            return this;
15469        }
15470
15471        HandlerParams setTraceCookie(int traceCookie) {
15472            this.traceCookie = traceCookie;
15473            return this;
15474        }
15475
15476        final boolean startCopy() {
15477            boolean res;
15478            try {
15479                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
15480
15481                if (++mRetries > MAX_RETRIES) {
15482                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
15483                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
15484                    handleServiceError();
15485                    return false;
15486                } else {
15487                    handleStartCopy();
15488                    res = true;
15489                }
15490            } catch (RemoteException e) {
15491                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
15492                mHandler.sendEmptyMessage(MCS_RECONNECT);
15493                res = false;
15494            }
15495            handleReturnCode();
15496            return res;
15497        }
15498
15499        final void serviceError() {
15500            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
15501            handleServiceError();
15502            handleReturnCode();
15503        }
15504
15505        abstract void handleStartCopy() throws RemoteException;
15506        abstract void handleServiceError();
15507        abstract void handleReturnCode();
15508    }
15509
15510    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
15511        for (File path : paths) {
15512            try {
15513                mcs.clearDirectory(path.getAbsolutePath());
15514            } catch (RemoteException e) {
15515            }
15516        }
15517    }
15518
15519    static class OriginInfo {
15520        /**
15521         * Location where install is coming from, before it has been
15522         * copied/renamed into place. This could be a single monolithic APK
15523         * file, or a cluster directory. This location may be untrusted.
15524         */
15525        final File file;
15526        final String cid;
15527
15528        /**
15529         * Flag indicating that {@link #file} or {@link #cid} has already been
15530         * staged, meaning downstream users don't need to defensively copy the
15531         * contents.
15532         */
15533        final boolean staged;
15534
15535        /**
15536         * Flag indicating that {@link #file} or {@link #cid} is an already
15537         * installed app that is being moved.
15538         */
15539        final boolean existing;
15540
15541        final String resolvedPath;
15542        final File resolvedFile;
15543
15544        static OriginInfo fromNothing() {
15545            return new OriginInfo(null, null, false, false);
15546        }
15547
15548        static OriginInfo fromUntrustedFile(File file) {
15549            return new OriginInfo(file, null, false, false);
15550        }
15551
15552        static OriginInfo fromExistingFile(File file) {
15553            return new OriginInfo(file, null, false, true);
15554        }
15555
15556        static OriginInfo fromStagedFile(File file) {
15557            return new OriginInfo(file, null, true, false);
15558        }
15559
15560        static OriginInfo fromStagedContainer(String cid) {
15561            return new OriginInfo(null, cid, true, false);
15562        }
15563
15564        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
15565            this.file = file;
15566            this.cid = cid;
15567            this.staged = staged;
15568            this.existing = existing;
15569
15570            if (cid != null) {
15571                resolvedPath = PackageHelper.getSdDir(cid);
15572                resolvedFile = new File(resolvedPath);
15573            } else if (file != null) {
15574                resolvedPath = file.getAbsolutePath();
15575                resolvedFile = file;
15576            } else {
15577                resolvedPath = null;
15578                resolvedFile = null;
15579            }
15580        }
15581    }
15582
15583    static class MoveInfo {
15584        final int moveId;
15585        final String fromUuid;
15586        final String toUuid;
15587        final String packageName;
15588        final String dataAppName;
15589        final int appId;
15590        final String seinfo;
15591        final int targetSdkVersion;
15592
15593        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
15594                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
15595            this.moveId = moveId;
15596            this.fromUuid = fromUuid;
15597            this.toUuid = toUuid;
15598            this.packageName = packageName;
15599            this.dataAppName = dataAppName;
15600            this.appId = appId;
15601            this.seinfo = seinfo;
15602            this.targetSdkVersion = targetSdkVersion;
15603        }
15604    }
15605
15606    static class VerificationInfo {
15607        /** A constant used to indicate that a uid value is not present. */
15608        public static final int NO_UID = -1;
15609
15610        /** URI referencing where the package was downloaded from. */
15611        final Uri originatingUri;
15612
15613        /** HTTP referrer URI associated with the originatingURI. */
15614        final Uri referrer;
15615
15616        /** UID of the application that the install request originated from. */
15617        final int originatingUid;
15618
15619        /** UID of application requesting the install */
15620        final int installerUid;
15621
15622        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
15623            this.originatingUri = originatingUri;
15624            this.referrer = referrer;
15625            this.originatingUid = originatingUid;
15626            this.installerUid = installerUid;
15627        }
15628    }
15629
15630    class InstallParams extends HandlerParams {
15631        final OriginInfo origin;
15632        final MoveInfo move;
15633        final IPackageInstallObserver2 observer;
15634        int installFlags;
15635        final String installerPackageName;
15636        final String volumeUuid;
15637        private InstallArgs mArgs;
15638        private int mRet;
15639        final String packageAbiOverride;
15640        final String[] grantedRuntimePermissions;
15641        final VerificationInfo verificationInfo;
15642        final Certificate[][] certificates;
15643        final int installReason;
15644
15645        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15646                int installFlags, String installerPackageName, String volumeUuid,
15647                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
15648                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
15649            super(user);
15650            this.origin = origin;
15651            this.move = move;
15652            this.observer = observer;
15653            this.installFlags = installFlags;
15654            this.installerPackageName = installerPackageName;
15655            this.volumeUuid = volumeUuid;
15656            this.verificationInfo = verificationInfo;
15657            this.packageAbiOverride = packageAbiOverride;
15658            this.grantedRuntimePermissions = grantedPermissions;
15659            this.certificates = certificates;
15660            this.installReason = installReason;
15661        }
15662
15663        @Override
15664        public String toString() {
15665            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
15666                    + " file=" + origin.file + " cid=" + origin.cid + "}";
15667        }
15668
15669        private int installLocationPolicy(PackageInfoLite pkgLite) {
15670            String packageName = pkgLite.packageName;
15671            int installLocation = pkgLite.installLocation;
15672            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15673            // reader
15674            synchronized (mPackages) {
15675                // Currently installed package which the new package is attempting to replace or
15676                // null if no such package is installed.
15677                PackageParser.Package installedPkg = mPackages.get(packageName);
15678                // Package which currently owns the data which the new package will own if installed.
15679                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
15680                // will be null whereas dataOwnerPkg will contain information about the package
15681                // which was uninstalled while keeping its data.
15682                PackageParser.Package dataOwnerPkg = installedPkg;
15683                if (dataOwnerPkg  == null) {
15684                    PackageSetting ps = mSettings.mPackages.get(packageName);
15685                    if (ps != null) {
15686                        dataOwnerPkg = ps.pkg;
15687                    }
15688                }
15689
15690                if (dataOwnerPkg != null) {
15691                    // If installed, the package will get access to data left on the device by its
15692                    // predecessor. As a security measure, this is permited only if this is not a
15693                    // version downgrade or if the predecessor package is marked as debuggable and
15694                    // a downgrade is explicitly requested.
15695                    //
15696                    // On debuggable platform builds, downgrades are permitted even for
15697                    // non-debuggable packages to make testing easier. Debuggable platform builds do
15698                    // not offer security guarantees and thus it's OK to disable some security
15699                    // mechanisms to make debugging/testing easier on those builds. However, even on
15700                    // debuggable builds downgrades of packages are permitted only if requested via
15701                    // installFlags. This is because we aim to keep the behavior of debuggable
15702                    // platform builds as close as possible to the behavior of non-debuggable
15703                    // platform builds.
15704                    final boolean downgradeRequested =
15705                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
15706                    final boolean packageDebuggable =
15707                                (dataOwnerPkg.applicationInfo.flags
15708                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
15709                    final boolean downgradePermitted =
15710                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
15711                    if (!downgradePermitted) {
15712                        try {
15713                            checkDowngrade(dataOwnerPkg, pkgLite);
15714                        } catch (PackageManagerException e) {
15715                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
15716                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
15717                        }
15718                    }
15719                }
15720
15721                if (installedPkg != null) {
15722                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15723                        // Check for updated system application.
15724                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15725                            if (onSd) {
15726                                Slog.w(TAG, "Cannot install update to system app on sdcard");
15727                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
15728                            }
15729                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15730                        } else {
15731                            if (onSd) {
15732                                // Install flag overrides everything.
15733                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15734                            }
15735                            // If current upgrade specifies particular preference
15736                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
15737                                // Application explicitly specified internal.
15738                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15739                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
15740                                // App explictly prefers external. Let policy decide
15741                            } else {
15742                                // Prefer previous location
15743                                if (isExternal(installedPkg)) {
15744                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15745                                }
15746                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15747                            }
15748                        }
15749                    } else {
15750                        // Invalid install. Return error code
15751                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
15752                    }
15753                }
15754            }
15755            // All the special cases have been taken care of.
15756            // Return result based on recommended install location.
15757            if (onSd) {
15758                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15759            }
15760            return pkgLite.recommendedInstallLocation;
15761        }
15762
15763        /*
15764         * Invoke remote method to get package information and install
15765         * location values. Override install location based on default
15766         * policy if needed and then create install arguments based
15767         * on the install location.
15768         */
15769        public void handleStartCopy() throws RemoteException {
15770            int ret = PackageManager.INSTALL_SUCCEEDED;
15771
15772            // If we're already staged, we've firmly committed to an install location
15773            if (origin.staged) {
15774                if (origin.file != null) {
15775                    installFlags |= PackageManager.INSTALL_INTERNAL;
15776                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15777                } else if (origin.cid != null) {
15778                    installFlags |= PackageManager.INSTALL_EXTERNAL;
15779                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
15780                } else {
15781                    throw new IllegalStateException("Invalid stage location");
15782                }
15783            }
15784
15785            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15786            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
15787            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15788            PackageInfoLite pkgLite = null;
15789
15790            if (onInt && onSd) {
15791                // Check if both bits are set.
15792                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
15793                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15794            } else if (onSd && ephemeral) {
15795                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
15796                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15797            } else {
15798                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
15799                        packageAbiOverride);
15800
15801                if (DEBUG_EPHEMERAL && ephemeral) {
15802                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
15803                }
15804
15805                /*
15806                 * If we have too little free space, try to free cache
15807                 * before giving up.
15808                 */
15809                if (!origin.staged && pkgLite.recommendedInstallLocation
15810                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15811                    // TODO: focus freeing disk space on the target device
15812                    final StorageManager storage = StorageManager.from(mContext);
15813                    final long lowThreshold = storage.getStorageLowBytes(
15814                            Environment.getDataDirectory());
15815
15816                    final long sizeBytes = mContainerService.calculateInstalledSize(
15817                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
15818
15819                    try {
15820                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
15821                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
15822                                installFlags, packageAbiOverride);
15823                    } catch (InstallerException e) {
15824                        Slog.w(TAG, "Failed to free cache", e);
15825                    }
15826
15827                    /*
15828                     * The cache free must have deleted the file we
15829                     * downloaded to install.
15830                     *
15831                     * TODO: fix the "freeCache" call to not delete
15832                     *       the file we care about.
15833                     */
15834                    if (pkgLite.recommendedInstallLocation
15835                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15836                        pkgLite.recommendedInstallLocation
15837                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
15838                    }
15839                }
15840            }
15841
15842            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15843                int loc = pkgLite.recommendedInstallLocation;
15844                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
15845                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15846                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
15847                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
15848                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15849                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15850                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
15851                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
15852                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15853                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
15854                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
15855                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
15856                } else {
15857                    // Override with defaults if needed.
15858                    loc = installLocationPolicy(pkgLite);
15859                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
15860                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
15861                    } else if (!onSd && !onInt) {
15862                        // Override install location with flags
15863                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
15864                            // Set the flag to install on external media.
15865                            installFlags |= PackageManager.INSTALL_EXTERNAL;
15866                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
15867                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
15868                            if (DEBUG_EPHEMERAL) {
15869                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
15870                            }
15871                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
15872                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
15873                                    |PackageManager.INSTALL_INTERNAL);
15874                        } else {
15875                            // Make sure the flag for installing on external
15876                            // media is unset
15877                            installFlags |= PackageManager.INSTALL_INTERNAL;
15878                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15879                        }
15880                    }
15881                }
15882            }
15883
15884            final InstallArgs args = createInstallArgs(this);
15885            mArgs = args;
15886
15887            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15888                // TODO: http://b/22976637
15889                // Apps installed for "all" users use the device owner to verify the app
15890                UserHandle verifierUser = getUser();
15891                if (verifierUser == UserHandle.ALL) {
15892                    verifierUser = UserHandle.SYSTEM;
15893                }
15894
15895                /*
15896                 * Determine if we have any installed package verifiers. If we
15897                 * do, then we'll defer to them to verify the packages.
15898                 */
15899                final int requiredUid = mRequiredVerifierPackage == null ? -1
15900                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15901                                verifierUser.getIdentifier());
15902                final int installerUid =
15903                        verificationInfo == null ? -1 : verificationInfo.installerUid;
15904                if (!origin.existing && requiredUid != -1
15905                        && isVerificationEnabled(
15906                                verifierUser.getIdentifier(), installFlags, installerUid)) {
15907                    final Intent verification = new Intent(
15908                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
15909                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
15910                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
15911                            PACKAGE_MIME_TYPE);
15912                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15913
15914                    // Query all live verifiers based on current user state
15915                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
15916                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
15917
15918                    if (DEBUG_VERIFY) {
15919                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
15920                                + verification.toString() + " with " + pkgLite.verifiers.length
15921                                + " optional verifiers");
15922                    }
15923
15924                    final int verificationId = mPendingVerificationToken++;
15925
15926                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15927
15928                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
15929                            installerPackageName);
15930
15931                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
15932                            installFlags);
15933
15934                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
15935                            pkgLite.packageName);
15936
15937                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
15938                            pkgLite.versionCode);
15939
15940                    if (verificationInfo != null) {
15941                        if (verificationInfo.originatingUri != null) {
15942                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
15943                                    verificationInfo.originatingUri);
15944                        }
15945                        if (verificationInfo.referrer != null) {
15946                            verification.putExtra(Intent.EXTRA_REFERRER,
15947                                    verificationInfo.referrer);
15948                        }
15949                        if (verificationInfo.originatingUid >= 0) {
15950                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
15951                                    verificationInfo.originatingUid);
15952                        }
15953                        if (verificationInfo.installerUid >= 0) {
15954                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
15955                                    verificationInfo.installerUid);
15956                        }
15957                    }
15958
15959                    final PackageVerificationState verificationState = new PackageVerificationState(
15960                            requiredUid, args);
15961
15962                    mPendingVerification.append(verificationId, verificationState);
15963
15964                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
15965                            receivers, verificationState);
15966
15967                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
15968                    final long idleDuration = getVerificationTimeout();
15969
15970                    /*
15971                     * If any sufficient verifiers were listed in the package
15972                     * manifest, attempt to ask them.
15973                     */
15974                    if (sufficientVerifiers != null) {
15975                        final int N = sufficientVerifiers.size();
15976                        if (N == 0) {
15977                            Slog.i(TAG, "Additional verifiers required, but none installed.");
15978                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
15979                        } else {
15980                            for (int i = 0; i < N; i++) {
15981                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
15982                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15983                                        verifierComponent.getPackageName(), idleDuration,
15984                                        verifierUser.getIdentifier(), false, "package verifier");
15985
15986                                final Intent sufficientIntent = new Intent(verification);
15987                                sufficientIntent.setComponent(verifierComponent);
15988                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
15989                            }
15990                        }
15991                    }
15992
15993                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
15994                            mRequiredVerifierPackage, receivers);
15995                    if (ret == PackageManager.INSTALL_SUCCEEDED
15996                            && mRequiredVerifierPackage != null) {
15997                        Trace.asyncTraceBegin(
15998                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
15999                        /*
16000                         * Send the intent to the required verification agent,
16001                         * but only start the verification timeout after the
16002                         * target BroadcastReceivers have run.
16003                         */
16004                        verification.setComponent(requiredVerifierComponent);
16005                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
16006                                mRequiredVerifierPackage, idleDuration,
16007                                verifierUser.getIdentifier(), false, "package verifier");
16008                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
16009                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
16010                                new BroadcastReceiver() {
16011                                    @Override
16012                                    public void onReceive(Context context, Intent intent) {
16013                                        final Message msg = mHandler
16014                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
16015                                        msg.arg1 = verificationId;
16016                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
16017                                    }
16018                                }, null, 0, null, null);
16019
16020                        /*
16021                         * We don't want the copy to proceed until verification
16022                         * succeeds, so null out this field.
16023                         */
16024                        mArgs = null;
16025                    }
16026                } else {
16027                    /*
16028                     * No package verification is enabled, so immediately start
16029                     * the remote call to initiate copy using temporary file.
16030                     */
16031                    ret = args.copyApk(mContainerService, true);
16032                }
16033            }
16034
16035            mRet = ret;
16036        }
16037
16038        @Override
16039        void handleReturnCode() {
16040            // If mArgs is null, then MCS couldn't be reached. When it
16041            // reconnects, it will try again to install. At that point, this
16042            // will succeed.
16043            if (mArgs != null) {
16044                processPendingInstall(mArgs, mRet);
16045            }
16046        }
16047
16048        @Override
16049        void handleServiceError() {
16050            mArgs = createInstallArgs(this);
16051            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16052        }
16053
16054        public boolean isForwardLocked() {
16055            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16056        }
16057    }
16058
16059    /**
16060     * Used during creation of InstallArgs
16061     *
16062     * @param installFlags package installation flags
16063     * @return true if should be installed on external storage
16064     */
16065    private static boolean installOnExternalAsec(int installFlags) {
16066        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
16067            return false;
16068        }
16069        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
16070            return true;
16071        }
16072        return false;
16073    }
16074
16075    /**
16076     * Used during creation of InstallArgs
16077     *
16078     * @param installFlags package installation flags
16079     * @return true if should be installed as forward locked
16080     */
16081    private static boolean installForwardLocked(int installFlags) {
16082        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16083    }
16084
16085    private InstallArgs createInstallArgs(InstallParams params) {
16086        if (params.move != null) {
16087            return new MoveInstallArgs(params);
16088        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
16089            return new AsecInstallArgs(params);
16090        } else {
16091            return new FileInstallArgs(params);
16092        }
16093    }
16094
16095    /**
16096     * Create args that describe an existing installed package. Typically used
16097     * when cleaning up old installs, or used as a move source.
16098     */
16099    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
16100            String resourcePath, String[] instructionSets) {
16101        final boolean isInAsec;
16102        if (installOnExternalAsec(installFlags)) {
16103            /* Apps on SD card are always in ASEC containers. */
16104            isInAsec = true;
16105        } else if (installForwardLocked(installFlags)
16106                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
16107            /*
16108             * Forward-locked apps are only in ASEC containers if they're the
16109             * new style
16110             */
16111            isInAsec = true;
16112        } else {
16113            isInAsec = false;
16114        }
16115
16116        if (isInAsec) {
16117            return new AsecInstallArgs(codePath, instructionSets,
16118                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
16119        } else {
16120            return new FileInstallArgs(codePath, resourcePath, instructionSets);
16121        }
16122    }
16123
16124    static abstract class InstallArgs {
16125        /** @see InstallParams#origin */
16126        final OriginInfo origin;
16127        /** @see InstallParams#move */
16128        final MoveInfo move;
16129
16130        final IPackageInstallObserver2 observer;
16131        // Always refers to PackageManager flags only
16132        final int installFlags;
16133        final String installerPackageName;
16134        final String volumeUuid;
16135        final UserHandle user;
16136        final String abiOverride;
16137        final String[] installGrantPermissions;
16138        /** If non-null, drop an async trace when the install completes */
16139        final String traceMethod;
16140        final int traceCookie;
16141        final Certificate[][] certificates;
16142        final int installReason;
16143
16144        // The list of instruction sets supported by this app. This is currently
16145        // only used during the rmdex() phase to clean up resources. We can get rid of this
16146        // if we move dex files under the common app path.
16147        /* nullable */ String[] instructionSets;
16148
16149        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
16150                int installFlags, String installerPackageName, String volumeUuid,
16151                UserHandle user, String[] instructionSets,
16152                String abiOverride, String[] installGrantPermissions,
16153                String traceMethod, int traceCookie, Certificate[][] certificates,
16154                int installReason) {
16155            this.origin = origin;
16156            this.move = move;
16157            this.installFlags = installFlags;
16158            this.observer = observer;
16159            this.installerPackageName = installerPackageName;
16160            this.volumeUuid = volumeUuid;
16161            this.user = user;
16162            this.instructionSets = instructionSets;
16163            this.abiOverride = abiOverride;
16164            this.installGrantPermissions = installGrantPermissions;
16165            this.traceMethod = traceMethod;
16166            this.traceCookie = traceCookie;
16167            this.certificates = certificates;
16168            this.installReason = installReason;
16169        }
16170
16171        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
16172        abstract int doPreInstall(int status);
16173
16174        /**
16175         * Rename package into final resting place. All paths on the given
16176         * scanned package should be updated to reflect the rename.
16177         */
16178        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
16179        abstract int doPostInstall(int status, int uid);
16180
16181        /** @see PackageSettingBase#codePathString */
16182        abstract String getCodePath();
16183        /** @see PackageSettingBase#resourcePathString */
16184        abstract String getResourcePath();
16185
16186        // Need installer lock especially for dex file removal.
16187        abstract void cleanUpResourcesLI();
16188        abstract boolean doPostDeleteLI(boolean delete);
16189
16190        /**
16191         * Called before the source arguments are copied. This is used mostly
16192         * for MoveParams when it needs to read the source file to put it in the
16193         * destination.
16194         */
16195        int doPreCopy() {
16196            return PackageManager.INSTALL_SUCCEEDED;
16197        }
16198
16199        /**
16200         * Called after the source arguments are copied. This is used mostly for
16201         * MoveParams when it needs to read the source file to put it in the
16202         * destination.
16203         */
16204        int doPostCopy(int uid) {
16205            return PackageManager.INSTALL_SUCCEEDED;
16206        }
16207
16208        protected boolean isFwdLocked() {
16209            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16210        }
16211
16212        protected boolean isExternalAsec() {
16213            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16214        }
16215
16216        protected boolean isEphemeral() {
16217            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16218        }
16219
16220        UserHandle getUser() {
16221            return user;
16222        }
16223    }
16224
16225    void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
16226        if (!allCodePaths.isEmpty()) {
16227            if (instructionSets == null) {
16228                throw new IllegalStateException("instructionSet == null");
16229            }
16230            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
16231            for (String codePath : allCodePaths) {
16232                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
16233                    try {
16234                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
16235                    } catch (InstallerException ignored) {
16236                    }
16237                }
16238            }
16239        }
16240    }
16241
16242    /**
16243     * Logic to handle installation of non-ASEC applications, including copying
16244     * and renaming logic.
16245     */
16246    class FileInstallArgs extends InstallArgs {
16247        private File codeFile;
16248        private File resourceFile;
16249
16250        // Example topology:
16251        // /data/app/com.example/base.apk
16252        // /data/app/com.example/split_foo.apk
16253        // /data/app/com.example/lib/arm/libfoo.so
16254        // /data/app/com.example/lib/arm64/libfoo.so
16255        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
16256
16257        /** New install */
16258        FileInstallArgs(InstallParams params) {
16259            super(params.origin, params.move, params.observer, params.installFlags,
16260                    params.installerPackageName, params.volumeUuid,
16261                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
16262                    params.grantedRuntimePermissions,
16263                    params.traceMethod, params.traceCookie, params.certificates,
16264                    params.installReason);
16265            if (isFwdLocked()) {
16266                throw new IllegalArgumentException("Forward locking only supported in ASEC");
16267            }
16268        }
16269
16270        /** Existing install */
16271        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
16272            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
16273                    null, null, null, 0, null /*certificates*/,
16274                    PackageManager.INSTALL_REASON_UNKNOWN);
16275            this.codeFile = (codePath != null) ? new File(codePath) : null;
16276            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
16277        }
16278
16279        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16280            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
16281            try {
16282                return doCopyApk(imcs, temp);
16283            } finally {
16284                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16285            }
16286        }
16287
16288        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16289            if (origin.staged) {
16290                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
16291                codeFile = origin.file;
16292                resourceFile = origin.file;
16293                return PackageManager.INSTALL_SUCCEEDED;
16294            }
16295
16296            try {
16297                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16298                final File tempDir =
16299                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
16300                codeFile = tempDir;
16301                resourceFile = tempDir;
16302            } catch (IOException e) {
16303                Slog.w(TAG, "Failed to create copy file: " + e);
16304                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
16305            }
16306
16307            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
16308                @Override
16309                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
16310                    if (!FileUtils.isValidExtFilename(name)) {
16311                        throw new IllegalArgumentException("Invalid filename: " + name);
16312                    }
16313                    try {
16314                        final File file = new File(codeFile, name);
16315                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
16316                                O_RDWR | O_CREAT, 0644);
16317                        Os.chmod(file.getAbsolutePath(), 0644);
16318                        return new ParcelFileDescriptor(fd);
16319                    } catch (ErrnoException e) {
16320                        throw new RemoteException("Failed to open: " + e.getMessage());
16321                    }
16322                }
16323            };
16324
16325            int ret = PackageManager.INSTALL_SUCCEEDED;
16326            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
16327            if (ret != PackageManager.INSTALL_SUCCEEDED) {
16328                Slog.e(TAG, "Failed to copy package");
16329                return ret;
16330            }
16331
16332            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
16333            NativeLibraryHelper.Handle handle = null;
16334            try {
16335                handle = NativeLibraryHelper.Handle.create(codeFile);
16336                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
16337                        abiOverride);
16338            } catch (IOException e) {
16339                Slog.e(TAG, "Copying native libraries failed", e);
16340                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16341            } finally {
16342                IoUtils.closeQuietly(handle);
16343            }
16344
16345            return ret;
16346        }
16347
16348        int doPreInstall(int status) {
16349            if (status != PackageManager.INSTALL_SUCCEEDED) {
16350                cleanUp();
16351            }
16352            return status;
16353        }
16354
16355        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16356            if (status != PackageManager.INSTALL_SUCCEEDED) {
16357                cleanUp();
16358                return false;
16359            }
16360
16361            final File targetDir = codeFile.getParentFile();
16362            final File beforeCodeFile = codeFile;
16363            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
16364
16365            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
16366            try {
16367                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
16368            } catch (ErrnoException e) {
16369                Slog.w(TAG, "Failed to rename", e);
16370                return false;
16371            }
16372
16373            if (!SELinux.restoreconRecursive(afterCodeFile)) {
16374                Slog.w(TAG, "Failed to restorecon");
16375                return false;
16376            }
16377
16378            // Reflect the rename internally
16379            codeFile = afterCodeFile;
16380            resourceFile = afterCodeFile;
16381
16382            // Reflect the rename in scanned details
16383            pkg.setCodePath(afterCodeFile.getAbsolutePath());
16384            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16385                    afterCodeFile, pkg.baseCodePath));
16386            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16387                    afterCodeFile, pkg.splitCodePaths));
16388
16389            // Reflect the rename in app info
16390            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16391            pkg.setApplicationInfoCodePath(pkg.codePath);
16392            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16393            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16394            pkg.setApplicationInfoResourcePath(pkg.codePath);
16395            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16396            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16397
16398            return true;
16399        }
16400
16401        int doPostInstall(int status, int uid) {
16402            if (status != PackageManager.INSTALL_SUCCEEDED) {
16403                cleanUp();
16404            }
16405            return status;
16406        }
16407
16408        @Override
16409        String getCodePath() {
16410            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16411        }
16412
16413        @Override
16414        String getResourcePath() {
16415            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16416        }
16417
16418        private boolean cleanUp() {
16419            if (codeFile == null || !codeFile.exists()) {
16420                return false;
16421            }
16422
16423            removeCodePathLI(codeFile);
16424
16425            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
16426                resourceFile.delete();
16427            }
16428
16429            return true;
16430        }
16431
16432        void cleanUpResourcesLI() {
16433            // Try enumerating all code paths before deleting
16434            List<String> allCodePaths = Collections.EMPTY_LIST;
16435            if (codeFile != null && codeFile.exists()) {
16436                try {
16437                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16438                    allCodePaths = pkg.getAllCodePaths();
16439                } catch (PackageParserException e) {
16440                    // Ignored; we tried our best
16441                }
16442            }
16443
16444            cleanUp();
16445            removeDexFiles(allCodePaths, instructionSets);
16446        }
16447
16448        boolean doPostDeleteLI(boolean delete) {
16449            // XXX err, shouldn't we respect the delete flag?
16450            cleanUpResourcesLI();
16451            return true;
16452        }
16453    }
16454
16455    private boolean isAsecExternal(String cid) {
16456        final String asecPath = PackageHelper.getSdFilesystem(cid);
16457        return !asecPath.startsWith(mAsecInternalPath);
16458    }
16459
16460    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
16461            PackageManagerException {
16462        if (copyRet < 0) {
16463            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
16464                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
16465                throw new PackageManagerException(copyRet, message);
16466            }
16467        }
16468    }
16469
16470    /**
16471     * Extract the StorageManagerService "container ID" from the full code path of an
16472     * .apk.
16473     */
16474    static String cidFromCodePath(String fullCodePath) {
16475        int eidx = fullCodePath.lastIndexOf("/");
16476        String subStr1 = fullCodePath.substring(0, eidx);
16477        int sidx = subStr1.lastIndexOf("/");
16478        return subStr1.substring(sidx+1, eidx);
16479    }
16480
16481    /**
16482     * Logic to handle installation of ASEC applications, including copying and
16483     * renaming logic.
16484     */
16485    class AsecInstallArgs extends InstallArgs {
16486        static final String RES_FILE_NAME = "pkg.apk";
16487        static final String PUBLIC_RES_FILE_NAME = "res.zip";
16488
16489        String cid;
16490        String packagePath;
16491        String resourcePath;
16492
16493        /** New install */
16494        AsecInstallArgs(InstallParams params) {
16495            super(params.origin, params.move, params.observer, params.installFlags,
16496                    params.installerPackageName, params.volumeUuid,
16497                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
16498                    params.grantedRuntimePermissions,
16499                    params.traceMethod, params.traceCookie, params.certificates,
16500                    params.installReason);
16501        }
16502
16503        /** Existing install */
16504        AsecInstallArgs(String fullCodePath, String[] instructionSets,
16505                        boolean isExternal, boolean isForwardLocked) {
16506            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
16507                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
16508                    instructionSets, null, null, null, 0, null /*certificates*/,
16509                    PackageManager.INSTALL_REASON_UNKNOWN);
16510            // Hackily pretend we're still looking at a full code path
16511            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
16512                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
16513            }
16514
16515            // Extract cid from fullCodePath
16516            int eidx = fullCodePath.lastIndexOf("/");
16517            String subStr1 = fullCodePath.substring(0, eidx);
16518            int sidx = subStr1.lastIndexOf("/");
16519            cid = subStr1.substring(sidx+1, eidx);
16520            setMountPath(subStr1);
16521        }
16522
16523        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
16524            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
16525                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
16526                    instructionSets, null, null, null, 0, null /*certificates*/,
16527                    PackageManager.INSTALL_REASON_UNKNOWN);
16528            this.cid = cid;
16529            setMountPath(PackageHelper.getSdDir(cid));
16530        }
16531
16532        void createCopyFile() {
16533            cid = mInstallerService.allocateExternalStageCidLegacy();
16534        }
16535
16536        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16537            if (origin.staged && origin.cid != null) {
16538                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
16539                cid = origin.cid;
16540                setMountPath(PackageHelper.getSdDir(cid));
16541                return PackageManager.INSTALL_SUCCEEDED;
16542            }
16543
16544            if (temp) {
16545                createCopyFile();
16546            } else {
16547                /*
16548                 * Pre-emptively destroy the container since it's destroyed if
16549                 * copying fails due to it existing anyway.
16550                 */
16551                PackageHelper.destroySdDir(cid);
16552            }
16553
16554            final String newMountPath = imcs.copyPackageToContainer(
16555                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
16556                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
16557
16558            if (newMountPath != null) {
16559                setMountPath(newMountPath);
16560                return PackageManager.INSTALL_SUCCEEDED;
16561            } else {
16562                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16563            }
16564        }
16565
16566        @Override
16567        String getCodePath() {
16568            return packagePath;
16569        }
16570
16571        @Override
16572        String getResourcePath() {
16573            return resourcePath;
16574        }
16575
16576        int doPreInstall(int status) {
16577            if (status != PackageManager.INSTALL_SUCCEEDED) {
16578                // Destroy container
16579                PackageHelper.destroySdDir(cid);
16580            } else {
16581                boolean mounted = PackageHelper.isContainerMounted(cid);
16582                if (!mounted) {
16583                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
16584                            Process.SYSTEM_UID);
16585                    if (newMountPath != null) {
16586                        setMountPath(newMountPath);
16587                    } else {
16588                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16589                    }
16590                }
16591            }
16592            return status;
16593        }
16594
16595        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16596            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
16597            String newMountPath = null;
16598            if (PackageHelper.isContainerMounted(cid)) {
16599                // Unmount the container
16600                if (!PackageHelper.unMountSdDir(cid)) {
16601                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
16602                    return false;
16603                }
16604            }
16605            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
16606                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
16607                        " which might be stale. Will try to clean up.");
16608                // Clean up the stale container and proceed to recreate.
16609                if (!PackageHelper.destroySdDir(newCacheId)) {
16610                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
16611                    return false;
16612                }
16613                // Successfully cleaned up stale container. Try to rename again.
16614                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
16615                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
16616                            + " inspite of cleaning it up.");
16617                    return false;
16618                }
16619            }
16620            if (!PackageHelper.isContainerMounted(newCacheId)) {
16621                Slog.w(TAG, "Mounting container " + newCacheId);
16622                newMountPath = PackageHelper.mountSdDir(newCacheId,
16623                        getEncryptKey(), Process.SYSTEM_UID);
16624            } else {
16625                newMountPath = PackageHelper.getSdDir(newCacheId);
16626            }
16627            if (newMountPath == null) {
16628                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
16629                return false;
16630            }
16631            Log.i(TAG, "Succesfully renamed " + cid +
16632                    " to " + newCacheId +
16633                    " at new path: " + newMountPath);
16634            cid = newCacheId;
16635
16636            final File beforeCodeFile = new File(packagePath);
16637            setMountPath(newMountPath);
16638            final File afterCodeFile = new File(packagePath);
16639
16640            // Reflect the rename in scanned details
16641            pkg.setCodePath(afterCodeFile.getAbsolutePath());
16642            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16643                    afterCodeFile, pkg.baseCodePath));
16644            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16645                    afterCodeFile, pkg.splitCodePaths));
16646
16647            // Reflect the rename in app info
16648            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16649            pkg.setApplicationInfoCodePath(pkg.codePath);
16650            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16651            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16652            pkg.setApplicationInfoResourcePath(pkg.codePath);
16653            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16654            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16655
16656            return true;
16657        }
16658
16659        private void setMountPath(String mountPath) {
16660            final File mountFile = new File(mountPath);
16661
16662            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
16663            if (monolithicFile.exists()) {
16664                packagePath = monolithicFile.getAbsolutePath();
16665                if (isFwdLocked()) {
16666                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
16667                } else {
16668                    resourcePath = packagePath;
16669                }
16670            } else {
16671                packagePath = mountFile.getAbsolutePath();
16672                resourcePath = packagePath;
16673            }
16674        }
16675
16676        int doPostInstall(int status, int uid) {
16677            if (status != PackageManager.INSTALL_SUCCEEDED) {
16678                cleanUp();
16679            } else {
16680                final int groupOwner;
16681                final String protectedFile;
16682                if (isFwdLocked()) {
16683                    groupOwner = UserHandle.getSharedAppGid(uid);
16684                    protectedFile = RES_FILE_NAME;
16685                } else {
16686                    groupOwner = -1;
16687                    protectedFile = null;
16688                }
16689
16690                if (uid < Process.FIRST_APPLICATION_UID
16691                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
16692                    Slog.e(TAG, "Failed to finalize " + cid);
16693                    PackageHelper.destroySdDir(cid);
16694                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16695                }
16696
16697                boolean mounted = PackageHelper.isContainerMounted(cid);
16698                if (!mounted) {
16699                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
16700                }
16701            }
16702            return status;
16703        }
16704
16705        private void cleanUp() {
16706            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
16707
16708            // Destroy secure container
16709            PackageHelper.destroySdDir(cid);
16710        }
16711
16712        private List<String> getAllCodePaths() {
16713            final File codeFile = new File(getCodePath());
16714            if (codeFile != null && codeFile.exists()) {
16715                try {
16716                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16717                    return pkg.getAllCodePaths();
16718                } catch (PackageParserException e) {
16719                    // Ignored; we tried our best
16720                }
16721            }
16722            return Collections.EMPTY_LIST;
16723        }
16724
16725        void cleanUpResourcesLI() {
16726            // Enumerate all code paths before deleting
16727            cleanUpResourcesLI(getAllCodePaths());
16728        }
16729
16730        private void cleanUpResourcesLI(List<String> allCodePaths) {
16731            cleanUp();
16732            removeDexFiles(allCodePaths, instructionSets);
16733        }
16734
16735        String getPackageName() {
16736            return getAsecPackageName(cid);
16737        }
16738
16739        boolean doPostDeleteLI(boolean delete) {
16740            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
16741            final List<String> allCodePaths = getAllCodePaths();
16742            boolean mounted = PackageHelper.isContainerMounted(cid);
16743            if (mounted) {
16744                // Unmount first
16745                if (PackageHelper.unMountSdDir(cid)) {
16746                    mounted = false;
16747                }
16748            }
16749            if (!mounted && delete) {
16750                cleanUpResourcesLI(allCodePaths);
16751            }
16752            return !mounted;
16753        }
16754
16755        @Override
16756        int doPreCopy() {
16757            if (isFwdLocked()) {
16758                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
16759                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
16760                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16761                }
16762            }
16763
16764            return PackageManager.INSTALL_SUCCEEDED;
16765        }
16766
16767        @Override
16768        int doPostCopy(int uid) {
16769            if (isFwdLocked()) {
16770                if (uid < Process.FIRST_APPLICATION_UID
16771                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
16772                                RES_FILE_NAME)) {
16773                    Slog.e(TAG, "Failed to finalize " + cid);
16774                    PackageHelper.destroySdDir(cid);
16775                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16776                }
16777            }
16778
16779            return PackageManager.INSTALL_SUCCEEDED;
16780        }
16781    }
16782
16783    /**
16784     * Logic to handle movement of existing installed applications.
16785     */
16786    class MoveInstallArgs extends InstallArgs {
16787        private File codeFile;
16788        private File resourceFile;
16789
16790        /** New install */
16791        MoveInstallArgs(InstallParams params) {
16792            super(params.origin, params.move, params.observer, params.installFlags,
16793                    params.installerPackageName, params.volumeUuid,
16794                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
16795                    params.grantedRuntimePermissions,
16796                    params.traceMethod, params.traceCookie, params.certificates,
16797                    params.installReason);
16798        }
16799
16800        int copyApk(IMediaContainerService imcs, boolean temp) {
16801            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
16802                    + move.fromUuid + " to " + move.toUuid);
16803            synchronized (mInstaller) {
16804                try {
16805                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
16806                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
16807                } catch (InstallerException e) {
16808                    Slog.w(TAG, "Failed to move app", e);
16809                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16810                }
16811            }
16812
16813            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
16814            resourceFile = codeFile;
16815            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
16816
16817            return PackageManager.INSTALL_SUCCEEDED;
16818        }
16819
16820        int doPreInstall(int status) {
16821            if (status != PackageManager.INSTALL_SUCCEEDED) {
16822                cleanUp(move.toUuid);
16823            }
16824            return status;
16825        }
16826
16827        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16828            if (status != PackageManager.INSTALL_SUCCEEDED) {
16829                cleanUp(move.toUuid);
16830                return false;
16831            }
16832
16833            // Reflect the move in app info
16834            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16835            pkg.setApplicationInfoCodePath(pkg.codePath);
16836            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16837            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16838            pkg.setApplicationInfoResourcePath(pkg.codePath);
16839            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16840            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16841
16842            return true;
16843        }
16844
16845        int doPostInstall(int status, int uid) {
16846            if (status == PackageManager.INSTALL_SUCCEEDED) {
16847                cleanUp(move.fromUuid);
16848            } else {
16849                cleanUp(move.toUuid);
16850            }
16851            return status;
16852        }
16853
16854        @Override
16855        String getCodePath() {
16856            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16857        }
16858
16859        @Override
16860        String getResourcePath() {
16861            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16862        }
16863
16864        private boolean cleanUp(String volumeUuid) {
16865            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
16866                    move.dataAppName);
16867            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
16868            final int[] userIds = sUserManager.getUserIds();
16869            synchronized (mInstallLock) {
16870                // Clean up both app data and code
16871                // All package moves are frozen until finished
16872                for (int userId : userIds) {
16873                    try {
16874                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
16875                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
16876                    } catch (InstallerException e) {
16877                        Slog.w(TAG, String.valueOf(e));
16878                    }
16879                }
16880                removeCodePathLI(codeFile);
16881            }
16882            return true;
16883        }
16884
16885        void cleanUpResourcesLI() {
16886            throw new UnsupportedOperationException();
16887        }
16888
16889        boolean doPostDeleteLI(boolean delete) {
16890            throw new UnsupportedOperationException();
16891        }
16892    }
16893
16894    static String getAsecPackageName(String packageCid) {
16895        int idx = packageCid.lastIndexOf("-");
16896        if (idx == -1) {
16897            return packageCid;
16898        }
16899        return packageCid.substring(0, idx);
16900    }
16901
16902    // Utility method used to create code paths based on package name and available index.
16903    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
16904        String idxStr = "";
16905        int idx = 1;
16906        // Fall back to default value of idx=1 if prefix is not
16907        // part of oldCodePath
16908        if (oldCodePath != null) {
16909            String subStr = oldCodePath;
16910            // Drop the suffix right away
16911            if (suffix != null && subStr.endsWith(suffix)) {
16912                subStr = subStr.substring(0, subStr.length() - suffix.length());
16913            }
16914            // If oldCodePath already contains prefix find out the
16915            // ending index to either increment or decrement.
16916            int sidx = subStr.lastIndexOf(prefix);
16917            if (sidx != -1) {
16918                subStr = subStr.substring(sidx + prefix.length());
16919                if (subStr != null) {
16920                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
16921                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
16922                    }
16923                    try {
16924                        idx = Integer.parseInt(subStr);
16925                        if (idx <= 1) {
16926                            idx++;
16927                        } else {
16928                            idx--;
16929                        }
16930                    } catch(NumberFormatException e) {
16931                    }
16932                }
16933            }
16934        }
16935        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
16936        return prefix + idxStr;
16937    }
16938
16939    private File getNextCodePath(File targetDir, String packageName) {
16940        File result;
16941        SecureRandom random = new SecureRandom();
16942        byte[] bytes = new byte[16];
16943        do {
16944            random.nextBytes(bytes);
16945            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
16946            result = new File(targetDir, packageName + "-" + suffix);
16947        } while (result.exists());
16948        return result;
16949    }
16950
16951    // Utility method that returns the relative package path with respect
16952    // to the installation directory. Like say for /data/data/com.test-1.apk
16953    // string com.test-1 is returned.
16954    static String deriveCodePathName(String codePath) {
16955        if (codePath == null) {
16956            return null;
16957        }
16958        final File codeFile = new File(codePath);
16959        final String name = codeFile.getName();
16960        if (codeFile.isDirectory()) {
16961            return name;
16962        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
16963            final int lastDot = name.lastIndexOf('.');
16964            return name.substring(0, lastDot);
16965        } else {
16966            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
16967            return null;
16968        }
16969    }
16970
16971    static class PackageInstalledInfo {
16972        String name;
16973        int uid;
16974        // The set of users that originally had this package installed.
16975        int[] origUsers;
16976        // The set of users that now have this package installed.
16977        int[] newUsers;
16978        PackageParser.Package pkg;
16979        int returnCode;
16980        String returnMsg;
16981        PackageRemovedInfo removedInfo;
16982        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
16983
16984        public void setError(int code, String msg) {
16985            setReturnCode(code);
16986            setReturnMessage(msg);
16987            Slog.w(TAG, msg);
16988        }
16989
16990        public void setError(String msg, PackageParserException e) {
16991            setReturnCode(e.error);
16992            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16993            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16994            for (int i = 0; i < childCount; i++) {
16995                addedChildPackages.valueAt(i).setError(msg, e);
16996            }
16997            Slog.w(TAG, msg, e);
16998        }
16999
17000        public void setError(String msg, PackageManagerException e) {
17001            returnCode = e.error;
17002            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
17003            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17004            for (int i = 0; i < childCount; i++) {
17005                addedChildPackages.valueAt(i).setError(msg, e);
17006            }
17007            Slog.w(TAG, msg, e);
17008        }
17009
17010        public void setReturnCode(int returnCode) {
17011            this.returnCode = returnCode;
17012            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17013            for (int i = 0; i < childCount; i++) {
17014                addedChildPackages.valueAt(i).returnCode = returnCode;
17015            }
17016        }
17017
17018        private void setReturnMessage(String returnMsg) {
17019            this.returnMsg = returnMsg;
17020            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17021            for (int i = 0; i < childCount; i++) {
17022                addedChildPackages.valueAt(i).returnMsg = returnMsg;
17023            }
17024        }
17025
17026        // In some error cases we want to convey more info back to the observer
17027        String origPackage;
17028        String origPermission;
17029    }
17030
17031    /*
17032     * Install a non-existing package.
17033     */
17034    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
17035            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
17036            PackageInstalledInfo res, int installReason) {
17037        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
17038
17039        // Remember this for later, in case we need to rollback this install
17040        String pkgName = pkg.packageName;
17041
17042        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
17043
17044        synchronized(mPackages) {
17045            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
17046            if (renamedPackage != null) {
17047                // A package with the same name is already installed, though
17048                // it has been renamed to an older name.  The package we
17049                // are trying to install should be installed as an update to
17050                // the existing one, but that has not been requested, so bail.
17051                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
17052                        + " without first uninstalling package running as "
17053                        + renamedPackage);
17054                return;
17055            }
17056            if (mPackages.containsKey(pkgName)) {
17057                // Don't allow installation over an existing package with the same name.
17058                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
17059                        + " without first uninstalling.");
17060                return;
17061            }
17062        }
17063
17064        try {
17065            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
17066                    System.currentTimeMillis(), user);
17067
17068            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
17069
17070            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17071                prepareAppDataAfterInstallLIF(newPackage);
17072
17073            } else {
17074                // Remove package from internal structures, but keep around any
17075                // data that might have already existed
17076                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
17077                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
17078            }
17079        } catch (PackageManagerException e) {
17080            res.setError("Package couldn't be installed in " + pkg.codePath, e);
17081        }
17082
17083        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17084    }
17085
17086    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
17087        // Can't rotate keys during boot or if sharedUser.
17088        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
17089                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
17090            return false;
17091        }
17092        // app is using upgradeKeySets; make sure all are valid
17093        KeySetManagerService ksms = mSettings.mKeySetManagerService;
17094        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
17095        for (int i = 0; i < upgradeKeySets.length; i++) {
17096            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
17097                Slog.wtf(TAG, "Package "
17098                         + (oldPs.name != null ? oldPs.name : "<null>")
17099                         + " contains upgrade-key-set reference to unknown key-set: "
17100                         + upgradeKeySets[i]
17101                         + " reverting to signatures check.");
17102                return false;
17103            }
17104        }
17105        return true;
17106    }
17107
17108    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
17109        // Upgrade keysets are being used.  Determine if new package has a superset of the
17110        // required keys.
17111        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
17112        KeySetManagerService ksms = mSettings.mKeySetManagerService;
17113        for (int i = 0; i < upgradeKeySets.length; i++) {
17114            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
17115            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
17116                return true;
17117            }
17118        }
17119        return false;
17120    }
17121
17122    private static void updateDigest(MessageDigest digest, File file) throws IOException {
17123        try (DigestInputStream digestStream =
17124                new DigestInputStream(new FileInputStream(file), digest)) {
17125            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
17126        }
17127    }
17128
17129    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
17130            UserHandle user, String installerPackageName, PackageInstalledInfo res,
17131            int installReason) {
17132        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17133
17134        final PackageParser.Package oldPackage;
17135        final PackageSetting ps;
17136        final String pkgName = pkg.packageName;
17137        final int[] allUsers;
17138        final int[] installedUsers;
17139
17140        synchronized(mPackages) {
17141            oldPackage = mPackages.get(pkgName);
17142            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
17143
17144            // don't allow upgrade to target a release SDK from a pre-release SDK
17145            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
17146                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17147            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
17148                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17149            if (oldTargetsPreRelease
17150                    && !newTargetsPreRelease
17151                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
17152                Slog.w(TAG, "Can't install package targeting released sdk");
17153                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
17154                return;
17155            }
17156
17157            ps = mSettings.mPackages.get(pkgName);
17158
17159            // verify signatures are valid
17160            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
17161                if (!checkUpgradeKeySetLP(ps, pkg)) {
17162                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17163                            "New package not signed by keys specified by upgrade-keysets: "
17164                                    + pkgName);
17165                    return;
17166                }
17167            } else {
17168                // default to original signature matching
17169                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
17170                        != PackageManager.SIGNATURE_MATCH) {
17171                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17172                            "New package has a different signature: " + pkgName);
17173                    return;
17174                }
17175            }
17176
17177            // don't allow a system upgrade unless the upgrade hash matches
17178            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
17179                byte[] digestBytes = null;
17180                try {
17181                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
17182                    updateDigest(digest, new File(pkg.baseCodePath));
17183                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
17184                        for (String path : pkg.splitCodePaths) {
17185                            updateDigest(digest, new File(path));
17186                        }
17187                    }
17188                    digestBytes = digest.digest();
17189                } catch (NoSuchAlgorithmException | IOException e) {
17190                    res.setError(INSTALL_FAILED_INVALID_APK,
17191                            "Could not compute hash: " + pkgName);
17192                    return;
17193                }
17194                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
17195                    res.setError(INSTALL_FAILED_INVALID_APK,
17196                            "New package fails restrict-update check: " + pkgName);
17197                    return;
17198                }
17199                // retain upgrade restriction
17200                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
17201            }
17202
17203            // Check for shared user id changes
17204            String invalidPackageName =
17205                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
17206            if (invalidPackageName != null) {
17207                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
17208                        "Package " + invalidPackageName + " tried to change user "
17209                                + oldPackage.mSharedUserId);
17210                return;
17211            }
17212
17213            // In case of rollback, remember per-user/profile install state
17214            allUsers = sUserManager.getUserIds();
17215            installedUsers = ps.queryInstalledUsers(allUsers, true);
17216
17217            // don't allow an upgrade from full to ephemeral
17218            if (isInstantApp) {
17219                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
17220                    for (int currentUser : allUsers) {
17221                        if (!ps.getInstantApp(currentUser)) {
17222                            // can't downgrade from full to instant
17223                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17224                                    + " for user: " + currentUser);
17225                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17226                            return;
17227                        }
17228                    }
17229                } else if (!ps.getInstantApp(user.getIdentifier())) {
17230                    // can't downgrade from full to instant
17231                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17232                            + " for user: " + user.getIdentifier());
17233                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17234                    return;
17235                }
17236            }
17237        }
17238
17239        // Update what is removed
17240        res.removedInfo = new PackageRemovedInfo(this);
17241        res.removedInfo.uid = oldPackage.applicationInfo.uid;
17242        res.removedInfo.removedPackage = oldPackage.packageName;
17243        res.removedInfo.installerPackageName = ps.installerPackageName;
17244        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
17245        res.removedInfo.isUpdate = true;
17246        res.removedInfo.origUsers = installedUsers;
17247        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
17248        for (int i = 0; i < installedUsers.length; i++) {
17249            final int userId = installedUsers[i];
17250            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
17251        }
17252
17253        final int childCount = (oldPackage.childPackages != null)
17254                ? oldPackage.childPackages.size() : 0;
17255        for (int i = 0; i < childCount; i++) {
17256            boolean childPackageUpdated = false;
17257            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
17258            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17259            if (res.addedChildPackages != null) {
17260                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17261                if (childRes != null) {
17262                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
17263                    childRes.removedInfo.removedPackage = childPkg.packageName;
17264                    if (childPs != null) {
17265                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17266                    }
17267                    childRes.removedInfo.isUpdate = true;
17268                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
17269                    childPackageUpdated = true;
17270                }
17271            }
17272            if (!childPackageUpdated) {
17273                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
17274                childRemovedRes.removedPackage = childPkg.packageName;
17275                if (childPs != null) {
17276                    childRemovedRes.installerPackageName = childPs.installerPackageName;
17277                }
17278                childRemovedRes.isUpdate = false;
17279                childRemovedRes.dataRemoved = true;
17280                synchronized (mPackages) {
17281                    if (childPs != null) {
17282                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
17283                    }
17284                }
17285                if (res.removedInfo.removedChildPackages == null) {
17286                    res.removedInfo.removedChildPackages = new ArrayMap<>();
17287                }
17288                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
17289            }
17290        }
17291
17292        boolean sysPkg = (isSystemApp(oldPackage));
17293        if (sysPkg) {
17294            // Set the system/privileged flags as needed
17295            final boolean privileged =
17296                    (oldPackage.applicationInfo.privateFlags
17297                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17298            final int systemPolicyFlags = policyFlags
17299                    | PackageParser.PARSE_IS_SYSTEM
17300                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
17301
17302            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
17303                    user, allUsers, installerPackageName, res, installReason);
17304        } else {
17305            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
17306                    user, allUsers, installerPackageName, res, installReason);
17307        }
17308    }
17309
17310    @Override
17311    public List<String> getPreviousCodePaths(String packageName) {
17312        final int callingUid = Binder.getCallingUid();
17313        final List<String> result = new ArrayList<>();
17314        if (getInstantAppPackageName(callingUid) != null) {
17315            return result;
17316        }
17317        final PackageSetting ps = mSettings.mPackages.get(packageName);
17318        if (ps != null
17319                && ps.oldCodePaths != null
17320                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
17321            result.addAll(ps.oldCodePaths);
17322        }
17323        return result;
17324    }
17325
17326    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
17327            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17328            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17329            int installReason) {
17330        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
17331                + deletedPackage);
17332
17333        String pkgName = deletedPackage.packageName;
17334        boolean deletedPkg = true;
17335        boolean addedPkg = false;
17336        boolean updatedSettings = false;
17337        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
17338        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
17339                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
17340
17341        final long origUpdateTime = (pkg.mExtras != null)
17342                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
17343
17344        // First delete the existing package while retaining the data directory
17345        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17346                res.removedInfo, true, pkg)) {
17347            // If the existing package wasn't successfully deleted
17348            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
17349            deletedPkg = false;
17350        } else {
17351            // Successfully deleted the old package; proceed with replace.
17352
17353            // If deleted package lived in a container, give users a chance to
17354            // relinquish resources before killing.
17355            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
17356                if (DEBUG_INSTALL) {
17357                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
17358                }
17359                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
17360                final ArrayList<String> pkgList = new ArrayList<String>(1);
17361                pkgList.add(deletedPackage.applicationInfo.packageName);
17362                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
17363            }
17364
17365            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17366                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17367            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17368
17369            try {
17370                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
17371                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
17372                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17373                        installReason);
17374
17375                // Update the in-memory copy of the previous code paths.
17376                PackageSetting ps = mSettings.mPackages.get(pkgName);
17377                if (!killApp) {
17378                    if (ps.oldCodePaths == null) {
17379                        ps.oldCodePaths = new ArraySet<>();
17380                    }
17381                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
17382                    if (deletedPackage.splitCodePaths != null) {
17383                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
17384                    }
17385                } else {
17386                    ps.oldCodePaths = null;
17387                }
17388                if (ps.childPackageNames != null) {
17389                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
17390                        final String childPkgName = ps.childPackageNames.get(i);
17391                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
17392                        childPs.oldCodePaths = ps.oldCodePaths;
17393                    }
17394                }
17395                // set instant app status, but, only if it's explicitly specified
17396                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17397                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
17398                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
17399                prepareAppDataAfterInstallLIF(newPackage);
17400                addedPkg = true;
17401                mDexManager.notifyPackageUpdated(newPackage.packageName,
17402                        newPackage.baseCodePath, newPackage.splitCodePaths);
17403            } catch (PackageManagerException e) {
17404                res.setError("Package couldn't be installed in " + pkg.codePath, e);
17405            }
17406        }
17407
17408        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17409            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
17410
17411            // Revert all internal state mutations and added folders for the failed install
17412            if (addedPkg) {
17413                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17414                        res.removedInfo, true, null);
17415            }
17416
17417            // Restore the old package
17418            if (deletedPkg) {
17419                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
17420                File restoreFile = new File(deletedPackage.codePath);
17421                // Parse old package
17422                boolean oldExternal = isExternal(deletedPackage);
17423                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
17424                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
17425                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
17426                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
17427                try {
17428                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
17429                            null);
17430                } catch (PackageManagerException e) {
17431                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
17432                            + e.getMessage());
17433                    return;
17434                }
17435
17436                synchronized (mPackages) {
17437                    // Ensure the installer package name up to date
17438                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17439
17440                    // Update permissions for restored package
17441                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17442
17443                    mSettings.writeLPr();
17444                }
17445
17446                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
17447            }
17448        } else {
17449            synchronized (mPackages) {
17450                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
17451                if (ps != null) {
17452                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
17453                    if (res.removedInfo.removedChildPackages != null) {
17454                        final int childCount = res.removedInfo.removedChildPackages.size();
17455                        // Iterate in reverse as we may modify the collection
17456                        for (int i = childCount - 1; i >= 0; i--) {
17457                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
17458                            if (res.addedChildPackages.containsKey(childPackageName)) {
17459                                res.removedInfo.removedChildPackages.removeAt(i);
17460                            } else {
17461                                PackageRemovedInfo childInfo = res.removedInfo
17462                                        .removedChildPackages.valueAt(i);
17463                                childInfo.removedForAllUsers = mPackages.get(
17464                                        childInfo.removedPackage) == null;
17465                            }
17466                        }
17467                    }
17468                }
17469            }
17470        }
17471    }
17472
17473    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
17474            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17475            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17476            int installReason) {
17477        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
17478                + ", old=" + deletedPackage);
17479
17480        final boolean disabledSystem;
17481
17482        // Remove existing system package
17483        removePackageLI(deletedPackage, true);
17484
17485        synchronized (mPackages) {
17486            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
17487        }
17488        if (!disabledSystem) {
17489            // We didn't need to disable the .apk as a current system package,
17490            // which means we are replacing another update that is already
17491            // installed.  We need to make sure to delete the older one's .apk.
17492            res.removedInfo.args = createInstallArgsForExisting(0,
17493                    deletedPackage.applicationInfo.getCodePath(),
17494                    deletedPackage.applicationInfo.getResourcePath(),
17495                    getAppDexInstructionSets(deletedPackage.applicationInfo));
17496        } else {
17497            res.removedInfo.args = null;
17498        }
17499
17500        // Successfully disabled the old package. Now proceed with re-installation
17501        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17502                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17503        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17504
17505        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17506        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
17507                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
17508
17509        PackageParser.Package newPackage = null;
17510        try {
17511            // Add the package to the internal data structures
17512            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
17513
17514            // Set the update and install times
17515            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
17516            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
17517                    System.currentTimeMillis());
17518
17519            // Update the package dynamic state if succeeded
17520            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17521                // Now that the install succeeded make sure we remove data
17522                // directories for any child package the update removed.
17523                final int deletedChildCount = (deletedPackage.childPackages != null)
17524                        ? deletedPackage.childPackages.size() : 0;
17525                final int newChildCount = (newPackage.childPackages != null)
17526                        ? newPackage.childPackages.size() : 0;
17527                for (int i = 0; i < deletedChildCount; i++) {
17528                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
17529                    boolean childPackageDeleted = true;
17530                    for (int j = 0; j < newChildCount; j++) {
17531                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
17532                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
17533                            childPackageDeleted = false;
17534                            break;
17535                        }
17536                    }
17537                    if (childPackageDeleted) {
17538                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
17539                                deletedChildPkg.packageName);
17540                        if (ps != null && res.removedInfo.removedChildPackages != null) {
17541                            PackageRemovedInfo removedChildRes = res.removedInfo
17542                                    .removedChildPackages.get(deletedChildPkg.packageName);
17543                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
17544                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
17545                        }
17546                    }
17547                }
17548
17549                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17550                        installReason);
17551                prepareAppDataAfterInstallLIF(newPackage);
17552
17553                mDexManager.notifyPackageUpdated(newPackage.packageName,
17554                            newPackage.baseCodePath, newPackage.splitCodePaths);
17555            }
17556        } catch (PackageManagerException e) {
17557            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
17558            res.setError("Package couldn't be installed in " + pkg.codePath, e);
17559        }
17560
17561        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17562            // Re installation failed. Restore old information
17563            // Remove new pkg information
17564            if (newPackage != null) {
17565                removeInstalledPackageLI(newPackage, true);
17566            }
17567            // Add back the old system package
17568            try {
17569                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
17570            } catch (PackageManagerException e) {
17571                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
17572            }
17573
17574            synchronized (mPackages) {
17575                if (disabledSystem) {
17576                    enableSystemPackageLPw(deletedPackage);
17577                }
17578
17579                // Ensure the installer package name up to date
17580                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17581
17582                // Update permissions for restored package
17583                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17584
17585                mSettings.writeLPr();
17586            }
17587
17588            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
17589                    + " after failed upgrade");
17590        }
17591    }
17592
17593    /**
17594     * Checks whether the parent or any of the child packages have a change shared
17595     * user. For a package to be a valid update the shred users of the parent and
17596     * the children should match. We may later support changing child shared users.
17597     * @param oldPkg The updated package.
17598     * @param newPkg The update package.
17599     * @return The shared user that change between the versions.
17600     */
17601    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
17602            PackageParser.Package newPkg) {
17603        // Check parent shared user
17604        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
17605            return newPkg.packageName;
17606        }
17607        // Check child shared users
17608        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
17609        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
17610        for (int i = 0; i < newChildCount; i++) {
17611            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
17612            // If this child was present, did it have the same shared user?
17613            for (int j = 0; j < oldChildCount; j++) {
17614                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
17615                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
17616                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
17617                    return newChildPkg.packageName;
17618                }
17619            }
17620        }
17621        return null;
17622    }
17623
17624    private void removeNativeBinariesLI(PackageSetting ps) {
17625        // Remove the lib path for the parent package
17626        if (ps != null) {
17627            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
17628            // Remove the lib path for the child packages
17629            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
17630            for (int i = 0; i < childCount; i++) {
17631                PackageSetting childPs = null;
17632                synchronized (mPackages) {
17633                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
17634                }
17635                if (childPs != null) {
17636                    NativeLibraryHelper.removeNativeBinariesLI(childPs
17637                            .legacyNativeLibraryPathString);
17638                }
17639            }
17640        }
17641    }
17642
17643    private void enableSystemPackageLPw(PackageParser.Package pkg) {
17644        // Enable the parent package
17645        mSettings.enableSystemPackageLPw(pkg.packageName);
17646        // Enable the child packages
17647        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17648        for (int i = 0; i < childCount; i++) {
17649            PackageParser.Package childPkg = pkg.childPackages.get(i);
17650            mSettings.enableSystemPackageLPw(childPkg.packageName);
17651        }
17652    }
17653
17654    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
17655            PackageParser.Package newPkg) {
17656        // Disable the parent package (parent always replaced)
17657        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
17658        // Disable the child packages
17659        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
17660        for (int i = 0; i < childCount; i++) {
17661            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
17662            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
17663            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
17664        }
17665        return disabled;
17666    }
17667
17668    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
17669            String installerPackageName) {
17670        // Enable the parent package
17671        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
17672        // Enable the child packages
17673        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17674        for (int i = 0; i < childCount; i++) {
17675            PackageParser.Package childPkg = pkg.childPackages.get(i);
17676            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
17677        }
17678    }
17679
17680    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
17681        // Collect all used permissions in the UID
17682        ArraySet<String> usedPermissions = new ArraySet<>();
17683        final int packageCount = su.packages.size();
17684        for (int i = 0; i < packageCount; i++) {
17685            PackageSetting ps = su.packages.valueAt(i);
17686            if (ps.pkg == null) {
17687                continue;
17688            }
17689            final int requestedPermCount = ps.pkg.requestedPermissions.size();
17690            for (int j = 0; j < requestedPermCount; j++) {
17691                String permission = ps.pkg.requestedPermissions.get(j);
17692                BasePermission bp = mSettings.mPermissions.get(permission);
17693                if (bp != null) {
17694                    usedPermissions.add(permission);
17695                }
17696            }
17697        }
17698
17699        PermissionsState permissionsState = su.getPermissionsState();
17700        // Prune install permissions
17701        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
17702        final int installPermCount = installPermStates.size();
17703        for (int i = installPermCount - 1; i >= 0;  i--) {
17704            PermissionState permissionState = installPermStates.get(i);
17705            if (!usedPermissions.contains(permissionState.getName())) {
17706                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
17707                if (bp != null) {
17708                    permissionsState.revokeInstallPermission(bp);
17709                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
17710                            PackageManager.MASK_PERMISSION_FLAGS, 0);
17711                }
17712            }
17713        }
17714
17715        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
17716
17717        // Prune runtime permissions
17718        for (int userId : allUserIds) {
17719            List<PermissionState> runtimePermStates = permissionsState
17720                    .getRuntimePermissionStates(userId);
17721            final int runtimePermCount = runtimePermStates.size();
17722            for (int i = runtimePermCount - 1; i >= 0; i--) {
17723                PermissionState permissionState = runtimePermStates.get(i);
17724                if (!usedPermissions.contains(permissionState.getName())) {
17725                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
17726                    if (bp != null) {
17727                        permissionsState.revokeRuntimePermission(bp, userId);
17728                        permissionsState.updatePermissionFlags(bp, userId,
17729                                PackageManager.MASK_PERMISSION_FLAGS, 0);
17730                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
17731                                runtimePermissionChangedUserIds, userId);
17732                    }
17733                }
17734            }
17735        }
17736
17737        return runtimePermissionChangedUserIds;
17738    }
17739
17740    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
17741            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
17742        // Update the parent package setting
17743        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
17744                res, user, installReason);
17745        // Update the child packages setting
17746        final int childCount = (newPackage.childPackages != null)
17747                ? newPackage.childPackages.size() : 0;
17748        for (int i = 0; i < childCount; i++) {
17749            PackageParser.Package childPackage = newPackage.childPackages.get(i);
17750            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
17751            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
17752                    childRes.origUsers, childRes, user, installReason);
17753        }
17754    }
17755
17756    private void updateSettingsInternalLI(PackageParser.Package newPackage,
17757            String installerPackageName, int[] allUsers, int[] installedForUsers,
17758            PackageInstalledInfo res, UserHandle user, int installReason) {
17759        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
17760
17761        String pkgName = newPackage.packageName;
17762        synchronized (mPackages) {
17763            //write settings. the installStatus will be incomplete at this stage.
17764            //note that the new package setting would have already been
17765            //added to mPackages. It hasn't been persisted yet.
17766            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
17767            // TODO: Remove this write? It's also written at the end of this method
17768            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
17769            mSettings.writeLPr();
17770            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17771        }
17772
17773        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
17774        synchronized (mPackages) {
17775            updatePermissionsLPw(newPackage.packageName, newPackage,
17776                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
17777                            ? UPDATE_PERMISSIONS_ALL : 0));
17778            // For system-bundled packages, we assume that installing an upgraded version
17779            // of the package implies that the user actually wants to run that new code,
17780            // so we enable the package.
17781            PackageSetting ps = mSettings.mPackages.get(pkgName);
17782            final int userId = user.getIdentifier();
17783            if (ps != null) {
17784                if (isSystemApp(newPackage)) {
17785                    if (DEBUG_INSTALL) {
17786                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
17787                    }
17788                    // Enable system package for requested users
17789                    if (res.origUsers != null) {
17790                        for (int origUserId : res.origUsers) {
17791                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
17792                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
17793                                        origUserId, installerPackageName);
17794                            }
17795                        }
17796                    }
17797                    // Also convey the prior install/uninstall state
17798                    if (allUsers != null && installedForUsers != null) {
17799                        for (int currentUserId : allUsers) {
17800                            final boolean installed = ArrayUtils.contains(
17801                                    installedForUsers, currentUserId);
17802                            if (DEBUG_INSTALL) {
17803                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
17804                            }
17805                            ps.setInstalled(installed, currentUserId);
17806                        }
17807                        // these install state changes will be persisted in the
17808                        // upcoming call to mSettings.writeLPr().
17809                    }
17810                }
17811                // It's implied that when a user requests installation, they want the app to be
17812                // installed and enabled.
17813                if (userId != UserHandle.USER_ALL) {
17814                    ps.setInstalled(true, userId);
17815                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
17816                }
17817
17818                // When replacing an existing package, preserve the original install reason for all
17819                // users that had the package installed before.
17820                final Set<Integer> previousUserIds = new ArraySet<>();
17821                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
17822                    final int installReasonCount = res.removedInfo.installReasons.size();
17823                    for (int i = 0; i < installReasonCount; i++) {
17824                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
17825                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
17826                        ps.setInstallReason(previousInstallReason, previousUserId);
17827                        previousUserIds.add(previousUserId);
17828                    }
17829                }
17830
17831                // Set install reason for users that are having the package newly installed.
17832                if (userId == UserHandle.USER_ALL) {
17833                    for (int currentUserId : sUserManager.getUserIds()) {
17834                        if (!previousUserIds.contains(currentUserId)) {
17835                            ps.setInstallReason(installReason, currentUserId);
17836                        }
17837                    }
17838                } else if (!previousUserIds.contains(userId)) {
17839                    ps.setInstallReason(installReason, userId);
17840                }
17841                mSettings.writeKernelMappingLPr(ps);
17842            }
17843            res.name = pkgName;
17844            res.uid = newPackage.applicationInfo.uid;
17845            res.pkg = newPackage;
17846            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
17847            mSettings.setInstallerPackageName(pkgName, installerPackageName);
17848            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17849            //to update install status
17850            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
17851            mSettings.writeLPr();
17852            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17853        }
17854
17855        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17856    }
17857
17858    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
17859        try {
17860            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
17861            installPackageLI(args, res);
17862        } finally {
17863            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17864        }
17865    }
17866
17867    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
17868        final int installFlags = args.installFlags;
17869        final String installerPackageName = args.installerPackageName;
17870        final String volumeUuid = args.volumeUuid;
17871        final File tmpPackageFile = new File(args.getCodePath());
17872        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
17873        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
17874                || (args.volumeUuid != null));
17875        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
17876        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
17877        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
17878        boolean replace = false;
17879        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
17880        if (args.move != null) {
17881            // moving a complete application; perform an initial scan on the new install location
17882            scanFlags |= SCAN_INITIAL;
17883        }
17884        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
17885            scanFlags |= SCAN_DONT_KILL_APP;
17886        }
17887        if (instantApp) {
17888            scanFlags |= SCAN_AS_INSTANT_APP;
17889        }
17890        if (fullApp) {
17891            scanFlags |= SCAN_AS_FULL_APP;
17892        }
17893
17894        // Result object to be returned
17895        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17896
17897        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
17898
17899        // Sanity check
17900        if (instantApp && (forwardLocked || onExternal)) {
17901            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
17902                    + " external=" + onExternal);
17903            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17904            return;
17905        }
17906
17907        // Retrieve PackageSettings and parse package
17908        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
17909                | PackageParser.PARSE_ENFORCE_CODE
17910                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
17911                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
17912                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
17913                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
17914        PackageParser pp = new PackageParser();
17915        pp.setSeparateProcesses(mSeparateProcesses);
17916        pp.setDisplayMetrics(mMetrics);
17917        pp.setCallback(mPackageParserCallback);
17918
17919        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
17920        final PackageParser.Package pkg;
17921        try {
17922            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
17923        } catch (PackageParserException e) {
17924            res.setError("Failed parse during installPackageLI", e);
17925            return;
17926        } finally {
17927            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17928        }
17929
17930        // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
17931        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
17932            Slog.w(TAG, "Instant app package " + pkg.packageName + " does not target O");
17933            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17934                    "Instant app package must target O");
17935            return;
17936        }
17937        if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
17938            Slog.w(TAG, "Instant app package " + pkg.packageName
17939                    + " does not target targetSandboxVersion 2");
17940            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17941                    "Instant app package must use targetSanboxVersion 2");
17942            return;
17943        }
17944
17945        if (pkg.applicationInfo.isStaticSharedLibrary()) {
17946            // Static shared libraries have synthetic package names
17947            renameStaticSharedLibraryPackage(pkg);
17948
17949            // No static shared libs on external storage
17950            if (onExternal) {
17951                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
17952                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17953                        "Packages declaring static-shared libs cannot be updated");
17954                return;
17955            }
17956        }
17957
17958        // If we are installing a clustered package add results for the children
17959        if (pkg.childPackages != null) {
17960            synchronized (mPackages) {
17961                final int childCount = pkg.childPackages.size();
17962                for (int i = 0; i < childCount; i++) {
17963                    PackageParser.Package childPkg = pkg.childPackages.get(i);
17964                    PackageInstalledInfo childRes = new PackageInstalledInfo();
17965                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17966                    childRes.pkg = childPkg;
17967                    childRes.name = childPkg.packageName;
17968                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17969                    if (childPs != null) {
17970                        childRes.origUsers = childPs.queryInstalledUsers(
17971                                sUserManager.getUserIds(), true);
17972                    }
17973                    if ((mPackages.containsKey(childPkg.packageName))) {
17974                        childRes.removedInfo = new PackageRemovedInfo(this);
17975                        childRes.removedInfo.removedPackage = childPkg.packageName;
17976                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17977                    }
17978                    if (res.addedChildPackages == null) {
17979                        res.addedChildPackages = new ArrayMap<>();
17980                    }
17981                    res.addedChildPackages.put(childPkg.packageName, childRes);
17982                }
17983            }
17984        }
17985
17986        // If package doesn't declare API override, mark that we have an install
17987        // time CPU ABI override.
17988        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
17989            pkg.cpuAbiOverride = args.abiOverride;
17990        }
17991
17992        String pkgName = res.name = pkg.packageName;
17993        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
17994            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
17995                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
17996                return;
17997            }
17998        }
17999
18000        try {
18001            // either use what we've been given or parse directly from the APK
18002            if (args.certificates != null) {
18003                try {
18004                    PackageParser.populateCertificates(pkg, args.certificates);
18005                } catch (PackageParserException e) {
18006                    // there was something wrong with the certificates we were given;
18007                    // try to pull them from the APK
18008                    PackageParser.collectCertificates(pkg, parseFlags);
18009                }
18010            } else {
18011                PackageParser.collectCertificates(pkg, parseFlags);
18012            }
18013        } catch (PackageParserException e) {
18014            res.setError("Failed collect during installPackageLI", e);
18015            return;
18016        }
18017
18018        // Get rid of all references to package scan path via parser.
18019        pp = null;
18020        String oldCodePath = null;
18021        boolean systemApp = false;
18022        synchronized (mPackages) {
18023            // Check if installing already existing package
18024            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
18025                String oldName = mSettings.getRenamedPackageLPr(pkgName);
18026                if (pkg.mOriginalPackages != null
18027                        && pkg.mOriginalPackages.contains(oldName)
18028                        && mPackages.containsKey(oldName)) {
18029                    // This package is derived from an original package,
18030                    // and this device has been updating from that original
18031                    // name.  We must continue using the original name, so
18032                    // rename the new package here.
18033                    pkg.setPackageName(oldName);
18034                    pkgName = pkg.packageName;
18035                    replace = true;
18036                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
18037                            + oldName + " pkgName=" + pkgName);
18038                } else if (mPackages.containsKey(pkgName)) {
18039                    // This package, under its official name, already exists
18040                    // on the device; we should replace it.
18041                    replace = true;
18042                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
18043                }
18044
18045                // Child packages are installed through the parent package
18046                if (pkg.parentPackage != null) {
18047                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
18048                            "Package " + pkg.packageName + " is child of package "
18049                                    + pkg.parentPackage.parentPackage + ". Child packages "
18050                                    + "can be updated only through the parent package.");
18051                    return;
18052                }
18053
18054                if (replace) {
18055                    // Prevent apps opting out from runtime permissions
18056                    PackageParser.Package oldPackage = mPackages.get(pkgName);
18057                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
18058                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
18059                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
18060                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
18061                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
18062                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
18063                                        + " doesn't support runtime permissions but the old"
18064                                        + " target SDK " + oldTargetSdk + " does.");
18065                        return;
18066                    }
18067                    // Prevent apps from downgrading their targetSandbox.
18068                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
18069                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
18070                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
18071                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18072                                "Package " + pkg.packageName + " new target sandbox "
18073                                + newTargetSandbox + " is incompatible with the previous value of"
18074                                + oldTargetSandbox + ".");
18075                        return;
18076                    }
18077
18078                    // Prevent installing of child packages
18079                    if (oldPackage.parentPackage != null) {
18080                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
18081                                "Package " + pkg.packageName + " is child of package "
18082                                        + oldPackage.parentPackage + ". Child packages "
18083                                        + "can be updated only through the parent package.");
18084                        return;
18085                    }
18086                }
18087            }
18088
18089            PackageSetting ps = mSettings.mPackages.get(pkgName);
18090            if (ps != null) {
18091                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
18092
18093                // Static shared libs have same package with different versions where
18094                // we internally use a synthetic package name to allow multiple versions
18095                // of the same package, therefore we need to compare signatures against
18096                // the package setting for the latest library version.
18097                PackageSetting signatureCheckPs = ps;
18098                if (pkg.applicationInfo.isStaticSharedLibrary()) {
18099                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
18100                    if (libraryEntry != null) {
18101                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
18102                    }
18103                }
18104
18105                // Quick sanity check that we're signed correctly if updating;
18106                // we'll check this again later when scanning, but we want to
18107                // bail early here before tripping over redefined permissions.
18108                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
18109                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
18110                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
18111                                + pkg.packageName + " upgrade keys do not match the "
18112                                + "previously installed version");
18113                        return;
18114                    }
18115                } else {
18116                    try {
18117                        verifySignaturesLP(signatureCheckPs, pkg);
18118                    } catch (PackageManagerException e) {
18119                        res.setError(e.error, e.getMessage());
18120                        return;
18121                    }
18122                }
18123
18124                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
18125                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
18126                    systemApp = (ps.pkg.applicationInfo.flags &
18127                            ApplicationInfo.FLAG_SYSTEM) != 0;
18128                }
18129                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18130            }
18131
18132            int N = pkg.permissions.size();
18133            for (int i = N-1; i >= 0; i--) {
18134                PackageParser.Permission perm = pkg.permissions.get(i);
18135                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
18136
18137                // Don't allow anyone but the system to define ephemeral permissions.
18138                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_EPHEMERAL) != 0
18139                        && !systemApp) {
18140                    Slog.w(TAG, "Non-System package " + pkg.packageName
18141                            + " attempting to delcare ephemeral permission "
18142                            + perm.info.name + "; Removing ephemeral.");
18143                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_EPHEMERAL;
18144                }
18145                // Check whether the newly-scanned package wants to define an already-defined perm
18146                if (bp != null) {
18147                    // If the defining package is signed with our cert, it's okay.  This
18148                    // also includes the "updating the same package" case, of course.
18149                    // "updating same package" could also involve key-rotation.
18150                    final boolean sigsOk;
18151                    if (bp.sourcePackage.equals(pkg.packageName)
18152                            && (bp.packageSetting instanceof PackageSetting)
18153                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
18154                                    scanFlags))) {
18155                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
18156                    } else {
18157                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
18158                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
18159                    }
18160                    if (!sigsOk) {
18161                        // If the owning package is the system itself, we log but allow
18162                        // install to proceed; we fail the install on all other permission
18163                        // redefinitions.
18164                        if (!bp.sourcePackage.equals("android")) {
18165                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
18166                                    + pkg.packageName + " attempting to redeclare permission "
18167                                    + perm.info.name + " already owned by " + bp.sourcePackage);
18168                            res.origPermission = perm.info.name;
18169                            res.origPackage = bp.sourcePackage;
18170                            return;
18171                        } else {
18172                            Slog.w(TAG, "Package " + pkg.packageName
18173                                    + " attempting to redeclare system permission "
18174                                    + perm.info.name + "; ignoring new declaration");
18175                            pkg.permissions.remove(i);
18176                        }
18177                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
18178                        // Prevent apps to change protection level to dangerous from any other
18179                        // type as this would allow a privilege escalation where an app adds a
18180                        // normal/signature permission in other app's group and later redefines
18181                        // it as dangerous leading to the group auto-grant.
18182                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
18183                                == PermissionInfo.PROTECTION_DANGEROUS) {
18184                            if (bp != null && !bp.isRuntime()) {
18185                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
18186                                        + "non-runtime permission " + perm.info.name
18187                                        + " to runtime; keeping old protection level");
18188                                perm.info.protectionLevel = bp.protectionLevel;
18189                            }
18190                        }
18191                    }
18192                }
18193            }
18194        }
18195
18196        if (systemApp) {
18197            if (onExternal) {
18198                // Abort update; system app can't be replaced with app on sdcard
18199                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
18200                        "Cannot install updates to system apps on sdcard");
18201                return;
18202            } else if (instantApp) {
18203                // Abort update; system app can't be replaced with an instant app
18204                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
18205                        "Cannot update a system app with an instant app");
18206                return;
18207            }
18208        }
18209
18210        if (args.move != null) {
18211            // We did an in-place move, so dex is ready to roll
18212            scanFlags |= SCAN_NO_DEX;
18213            scanFlags |= SCAN_MOVE;
18214
18215            synchronized (mPackages) {
18216                final PackageSetting ps = mSettings.mPackages.get(pkgName);
18217                if (ps == null) {
18218                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
18219                            "Missing settings for moved package " + pkgName);
18220                }
18221
18222                // We moved the entire application as-is, so bring over the
18223                // previously derived ABI information.
18224                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
18225                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
18226            }
18227
18228        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
18229            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
18230            scanFlags |= SCAN_NO_DEX;
18231
18232            try {
18233                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
18234                    args.abiOverride : pkg.cpuAbiOverride);
18235                final boolean extractNativeLibs = !pkg.isLibrary();
18236                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
18237                        extractNativeLibs, mAppLib32InstallDir);
18238            } catch (PackageManagerException pme) {
18239                Slog.e(TAG, "Error deriving application ABI", pme);
18240                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
18241                return;
18242            }
18243
18244            // Shared libraries for the package need to be updated.
18245            synchronized (mPackages) {
18246                try {
18247                    updateSharedLibrariesLPr(pkg, null);
18248                } catch (PackageManagerException e) {
18249                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18250                }
18251            }
18252
18253            // dexopt can take some time to complete, so, for instant apps, we skip this
18254            // step during installation. Instead, we'll take extra time the first time the
18255            // instant app starts. It's preferred to do it this way to provide continuous
18256            // progress to the user instead of mysteriously blocking somewhere in the
18257            // middle of running an instant app. The default behaviour can be overridden
18258            // via gservices.
18259            if (!instantApp || Global.getInt(
18260                        mContext.getContentResolver(), Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0) {
18261                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
18262                // Do not run PackageDexOptimizer through the local performDexOpt
18263                // method because `pkg` may not be in `mPackages` yet.
18264                //
18265                // Also, don't fail application installs if the dexopt step fails.
18266                DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName,
18267                        REASON_INSTALL,
18268                        DexoptOptions.DEXOPT_BOOT_COMPLETE);
18269                mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
18270                        null /* instructionSets */,
18271                        getOrCreateCompilerPackageStats(pkg),
18272                        mDexManager.isUsedByOtherApps(pkg.packageName),
18273                        dexoptOptions);
18274                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18275            }
18276
18277            // Notify BackgroundDexOptService that the package has been changed.
18278            // If this is an update of a package which used to fail to compile,
18279            // BDOS will remove it from its blacklist.
18280            // TODO: Layering violation
18281            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
18282        }
18283
18284        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
18285            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
18286            return;
18287        }
18288
18289        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
18290
18291        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
18292                "installPackageLI")) {
18293            if (replace) {
18294                if (pkg.applicationInfo.isStaticSharedLibrary()) {
18295                    // Static libs have a synthetic package name containing the version
18296                    // and cannot be updated as an update would get a new package name,
18297                    // unless this is the exact same version code which is useful for
18298                    // development.
18299                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
18300                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
18301                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
18302                                + "static-shared libs cannot be updated");
18303                        return;
18304                    }
18305                }
18306                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
18307                        installerPackageName, res, args.installReason);
18308            } else {
18309                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
18310                        args.user, installerPackageName, volumeUuid, res, args.installReason);
18311            }
18312        }
18313
18314        synchronized (mPackages) {
18315            final PackageSetting ps = mSettings.mPackages.get(pkgName);
18316            if (ps != null) {
18317                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18318                ps.setUpdateAvailable(false /*updateAvailable*/);
18319            }
18320
18321            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18322            for (int i = 0; i < childCount; i++) {
18323                PackageParser.Package childPkg = pkg.childPackages.get(i);
18324                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
18325                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
18326                if (childPs != null) {
18327                    childRes.newUsers = childPs.queryInstalledUsers(
18328                            sUserManager.getUserIds(), true);
18329                }
18330            }
18331
18332            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
18333                updateSequenceNumberLP(ps, res.newUsers);
18334                updateInstantAppInstallerLocked(pkgName);
18335            }
18336        }
18337    }
18338
18339    private void startIntentFilterVerifications(int userId, boolean replacing,
18340            PackageParser.Package pkg) {
18341        if (mIntentFilterVerifierComponent == null) {
18342            Slog.w(TAG, "No IntentFilter verification will not be done as "
18343                    + "there is no IntentFilterVerifier available!");
18344            return;
18345        }
18346
18347        final int verifierUid = getPackageUid(
18348                mIntentFilterVerifierComponent.getPackageName(),
18349                MATCH_DEBUG_TRIAGED_MISSING,
18350                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
18351
18352        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18353        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
18354        mHandler.sendMessage(msg);
18355
18356        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18357        for (int i = 0; i < childCount; i++) {
18358            PackageParser.Package childPkg = pkg.childPackages.get(i);
18359            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18360            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
18361            mHandler.sendMessage(msg);
18362        }
18363    }
18364
18365    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
18366            PackageParser.Package pkg) {
18367        int size = pkg.activities.size();
18368        if (size == 0) {
18369            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18370                    "No activity, so no need to verify any IntentFilter!");
18371            return;
18372        }
18373
18374        final boolean hasDomainURLs = hasDomainURLs(pkg);
18375        if (!hasDomainURLs) {
18376            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18377                    "No domain URLs, so no need to verify any IntentFilter!");
18378            return;
18379        }
18380
18381        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
18382                + " if any IntentFilter from the " + size
18383                + " Activities needs verification ...");
18384
18385        int count = 0;
18386        final String packageName = pkg.packageName;
18387
18388        synchronized (mPackages) {
18389            // If this is a new install and we see that we've already run verification for this
18390            // package, we have nothing to do: it means the state was restored from backup.
18391            if (!replacing) {
18392                IntentFilterVerificationInfo ivi =
18393                        mSettings.getIntentFilterVerificationLPr(packageName);
18394                if (ivi != null) {
18395                    if (DEBUG_DOMAIN_VERIFICATION) {
18396                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
18397                                + ivi.getStatusString());
18398                    }
18399                    return;
18400                }
18401            }
18402
18403            // If any filters need to be verified, then all need to be.
18404            boolean needToVerify = false;
18405            for (PackageParser.Activity a : pkg.activities) {
18406                for (ActivityIntentInfo filter : a.intents) {
18407                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
18408                        if (DEBUG_DOMAIN_VERIFICATION) {
18409                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
18410                        }
18411                        needToVerify = true;
18412                        break;
18413                    }
18414                }
18415            }
18416
18417            if (needToVerify) {
18418                final int verificationId = mIntentFilterVerificationToken++;
18419                for (PackageParser.Activity a : pkg.activities) {
18420                    for (ActivityIntentInfo filter : a.intents) {
18421                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
18422                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18423                                    "Verification needed for IntentFilter:" + filter.toString());
18424                            mIntentFilterVerifier.addOneIntentFilterVerification(
18425                                    verifierUid, userId, verificationId, filter, packageName);
18426                            count++;
18427                        }
18428                    }
18429                }
18430            }
18431        }
18432
18433        if (count > 0) {
18434            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
18435                    + " IntentFilter verification" + (count > 1 ? "s" : "")
18436                    +  " for userId:" + userId);
18437            mIntentFilterVerifier.startVerifications(userId);
18438        } else {
18439            if (DEBUG_DOMAIN_VERIFICATION) {
18440                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
18441            }
18442        }
18443    }
18444
18445    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
18446        final ComponentName cn  = filter.activity.getComponentName();
18447        final String packageName = cn.getPackageName();
18448
18449        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
18450                packageName);
18451        if (ivi == null) {
18452            return true;
18453        }
18454        int status = ivi.getStatus();
18455        switch (status) {
18456            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
18457            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
18458                return true;
18459
18460            default:
18461                // Nothing to do
18462                return false;
18463        }
18464    }
18465
18466    private static boolean isMultiArch(ApplicationInfo info) {
18467        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
18468    }
18469
18470    private static boolean isExternal(PackageParser.Package pkg) {
18471        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18472    }
18473
18474    private static boolean isExternal(PackageSetting ps) {
18475        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18476    }
18477
18478    private static boolean isSystemApp(PackageParser.Package pkg) {
18479        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
18480    }
18481
18482    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
18483        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
18484    }
18485
18486    private static boolean hasDomainURLs(PackageParser.Package pkg) {
18487        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
18488    }
18489
18490    private static boolean isSystemApp(PackageSetting ps) {
18491        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
18492    }
18493
18494    private static boolean isUpdatedSystemApp(PackageSetting ps) {
18495        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
18496    }
18497
18498    private int packageFlagsToInstallFlags(PackageSetting ps) {
18499        int installFlags = 0;
18500        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
18501            // This existing package was an external ASEC install when we have
18502            // the external flag without a UUID
18503            installFlags |= PackageManager.INSTALL_EXTERNAL;
18504        }
18505        if (ps.isForwardLocked()) {
18506            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
18507        }
18508        return installFlags;
18509    }
18510
18511    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
18512        if (isExternal(pkg)) {
18513            if (TextUtils.isEmpty(pkg.volumeUuid)) {
18514                return StorageManager.UUID_PRIMARY_PHYSICAL;
18515            } else {
18516                return pkg.volumeUuid;
18517            }
18518        } else {
18519            return StorageManager.UUID_PRIVATE_INTERNAL;
18520        }
18521    }
18522
18523    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
18524        if (isExternal(pkg)) {
18525            if (TextUtils.isEmpty(pkg.volumeUuid)) {
18526                return mSettings.getExternalVersion();
18527            } else {
18528                return mSettings.findOrCreateVersion(pkg.volumeUuid);
18529            }
18530        } else {
18531            return mSettings.getInternalVersion();
18532        }
18533    }
18534
18535    private void deleteTempPackageFiles() {
18536        final FilenameFilter filter = new FilenameFilter() {
18537            public boolean accept(File dir, String name) {
18538                return name.startsWith("vmdl") && name.endsWith(".tmp");
18539            }
18540        };
18541        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
18542            file.delete();
18543        }
18544    }
18545
18546    @Override
18547    public void deletePackageAsUser(String packageName, int versionCode,
18548            IPackageDeleteObserver observer, int userId, int flags) {
18549        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
18550                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
18551    }
18552
18553    @Override
18554    public void deletePackageVersioned(VersionedPackage versionedPackage,
18555            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
18556        final int callingUid = Binder.getCallingUid();
18557        mContext.enforceCallingOrSelfPermission(
18558                android.Manifest.permission.DELETE_PACKAGES, null);
18559        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
18560        Preconditions.checkNotNull(versionedPackage);
18561        Preconditions.checkNotNull(observer);
18562        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
18563                PackageManager.VERSION_CODE_HIGHEST,
18564                Integer.MAX_VALUE, "versionCode must be >= -1");
18565
18566        final String packageName = versionedPackage.getPackageName();
18567        final int versionCode = versionedPackage.getVersionCode();
18568        final String internalPackageName;
18569        synchronized (mPackages) {
18570            // Normalize package name to handle renamed packages and static libs
18571            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
18572                    versionedPackage.getVersionCode());
18573        }
18574
18575        final int uid = Binder.getCallingUid();
18576        if (!isOrphaned(internalPackageName)
18577                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
18578            try {
18579                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
18580                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
18581                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
18582                observer.onUserActionRequired(intent);
18583            } catch (RemoteException re) {
18584            }
18585            return;
18586        }
18587        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
18588        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
18589        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
18590            mContext.enforceCallingOrSelfPermission(
18591                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
18592                    "deletePackage for user " + userId);
18593        }
18594
18595        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
18596            try {
18597                observer.onPackageDeleted(packageName,
18598                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
18599            } catch (RemoteException re) {
18600            }
18601            return;
18602        }
18603
18604        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
18605            try {
18606                observer.onPackageDeleted(packageName,
18607                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
18608            } catch (RemoteException re) {
18609            }
18610            return;
18611        }
18612
18613        if (DEBUG_REMOVE) {
18614            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
18615                    + " deleteAllUsers: " + deleteAllUsers + " version="
18616                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
18617                    ? "VERSION_CODE_HIGHEST" : versionCode));
18618        }
18619        // Queue up an async operation since the package deletion may take a little while.
18620        mHandler.post(new Runnable() {
18621            public void run() {
18622                mHandler.removeCallbacks(this);
18623                int returnCode;
18624                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
18625                boolean doDeletePackage = true;
18626                if (ps != null) {
18627                    final boolean targetIsInstantApp =
18628                            ps.getInstantApp(UserHandle.getUserId(callingUid));
18629                    doDeletePackage = !targetIsInstantApp
18630                            || canViewInstantApps;
18631                }
18632                if (doDeletePackage) {
18633                    if (!deleteAllUsers) {
18634                        returnCode = deletePackageX(internalPackageName, versionCode,
18635                                userId, deleteFlags);
18636                    } else {
18637                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
18638                                internalPackageName, users);
18639                        // If nobody is blocking uninstall, proceed with delete for all users
18640                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
18641                            returnCode = deletePackageX(internalPackageName, versionCode,
18642                                    userId, deleteFlags);
18643                        } else {
18644                            // Otherwise uninstall individually for users with blockUninstalls=false
18645                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
18646                            for (int userId : users) {
18647                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
18648                                    returnCode = deletePackageX(internalPackageName, versionCode,
18649                                            userId, userFlags);
18650                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
18651                                        Slog.w(TAG, "Package delete failed for user " + userId
18652                                                + ", returnCode " + returnCode);
18653                                    }
18654                                }
18655                            }
18656                            // The app has only been marked uninstalled for certain users.
18657                            // We still need to report that delete was blocked
18658                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
18659                        }
18660                    }
18661                } else {
18662                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18663                }
18664                try {
18665                    observer.onPackageDeleted(packageName, returnCode, null);
18666                } catch (RemoteException e) {
18667                    Log.i(TAG, "Observer no longer exists.");
18668                } //end catch
18669            } //end run
18670        });
18671    }
18672
18673    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
18674        if (pkg.staticSharedLibName != null) {
18675            return pkg.manifestPackageName;
18676        }
18677        return pkg.packageName;
18678    }
18679
18680    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
18681        // Handle renamed packages
18682        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
18683        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
18684
18685        // Is this a static library?
18686        SparseArray<SharedLibraryEntry> versionedLib =
18687                mStaticLibsByDeclaringPackage.get(packageName);
18688        if (versionedLib == null || versionedLib.size() <= 0) {
18689            return packageName;
18690        }
18691
18692        // Figure out which lib versions the caller can see
18693        SparseIntArray versionsCallerCanSee = null;
18694        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
18695        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
18696                && callingAppId != Process.ROOT_UID) {
18697            versionsCallerCanSee = new SparseIntArray();
18698            String libName = versionedLib.valueAt(0).info.getName();
18699            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
18700            if (uidPackages != null) {
18701                for (String uidPackage : uidPackages) {
18702                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
18703                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
18704                    if (libIdx >= 0) {
18705                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
18706                        versionsCallerCanSee.append(libVersion, libVersion);
18707                    }
18708                }
18709            }
18710        }
18711
18712        // Caller can see nothing - done
18713        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
18714            return packageName;
18715        }
18716
18717        // Find the version the caller can see and the app version code
18718        SharedLibraryEntry highestVersion = null;
18719        final int versionCount = versionedLib.size();
18720        for (int i = 0; i < versionCount; i++) {
18721            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
18722            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
18723                    libEntry.info.getVersion()) < 0) {
18724                continue;
18725            }
18726            final int libVersionCode = libEntry.info.getDeclaringPackage().getVersionCode();
18727            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
18728                if (libVersionCode == versionCode) {
18729                    return libEntry.apk;
18730                }
18731            } else if (highestVersion == null) {
18732                highestVersion = libEntry;
18733            } else if (libVersionCode  > highestVersion.info
18734                    .getDeclaringPackage().getVersionCode()) {
18735                highestVersion = libEntry;
18736            }
18737        }
18738
18739        if (highestVersion != null) {
18740            return highestVersion.apk;
18741        }
18742
18743        return packageName;
18744    }
18745
18746    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
18747        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
18748              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
18749            return true;
18750        }
18751        final int callingUserId = UserHandle.getUserId(callingUid);
18752        // If the caller installed the pkgName, then allow it to silently uninstall.
18753        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
18754            return true;
18755        }
18756
18757        // Allow package verifier to silently uninstall.
18758        if (mRequiredVerifierPackage != null &&
18759                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
18760            return true;
18761        }
18762
18763        // Allow package uninstaller to silently uninstall.
18764        if (mRequiredUninstallerPackage != null &&
18765                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
18766            return true;
18767        }
18768
18769        // Allow storage manager to silently uninstall.
18770        if (mStorageManagerPackage != null &&
18771                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
18772            return true;
18773        }
18774
18775        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
18776        // uninstall for device owner provisioning.
18777        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
18778                == PERMISSION_GRANTED) {
18779            return true;
18780        }
18781
18782        return false;
18783    }
18784
18785    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
18786        int[] result = EMPTY_INT_ARRAY;
18787        for (int userId : userIds) {
18788            if (getBlockUninstallForUser(packageName, userId)) {
18789                result = ArrayUtils.appendInt(result, userId);
18790            }
18791        }
18792        return result;
18793    }
18794
18795    @Override
18796    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
18797        final int callingUid = Binder.getCallingUid();
18798        if (getInstantAppPackageName(callingUid) != null
18799                && !isCallerSameApp(packageName, callingUid)) {
18800            return false;
18801        }
18802        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
18803    }
18804
18805    private boolean isPackageDeviceAdmin(String packageName, int userId) {
18806        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
18807                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
18808        try {
18809            if (dpm != null) {
18810                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
18811                        /* callingUserOnly =*/ false);
18812                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
18813                        : deviceOwnerComponentName.getPackageName();
18814                // Does the package contains the device owner?
18815                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
18816                // this check is probably not needed, since DO should be registered as a device
18817                // admin on some user too. (Original bug for this: b/17657954)
18818                if (packageName.equals(deviceOwnerPackageName)) {
18819                    return true;
18820                }
18821                // Does it contain a device admin for any user?
18822                int[] users;
18823                if (userId == UserHandle.USER_ALL) {
18824                    users = sUserManager.getUserIds();
18825                } else {
18826                    users = new int[]{userId};
18827                }
18828                for (int i = 0; i < users.length; ++i) {
18829                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
18830                        return true;
18831                    }
18832                }
18833            }
18834        } catch (RemoteException e) {
18835        }
18836        return false;
18837    }
18838
18839    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
18840        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
18841    }
18842
18843    /**
18844     *  This method is an internal method that could be get invoked either
18845     *  to delete an installed package or to clean up a failed installation.
18846     *  After deleting an installed package, a broadcast is sent to notify any
18847     *  listeners that the package has been removed. For cleaning up a failed
18848     *  installation, the broadcast is not necessary since the package's
18849     *  installation wouldn't have sent the initial broadcast either
18850     *  The key steps in deleting a package are
18851     *  deleting the package information in internal structures like mPackages,
18852     *  deleting the packages base directories through installd
18853     *  updating mSettings to reflect current status
18854     *  persisting settings for later use
18855     *  sending a broadcast if necessary
18856     */
18857    int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
18858        final PackageRemovedInfo info = new PackageRemovedInfo(this);
18859        final boolean res;
18860
18861        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
18862                ? UserHandle.USER_ALL : userId;
18863
18864        if (isPackageDeviceAdmin(packageName, removeUser)) {
18865            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
18866            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
18867        }
18868
18869        PackageSetting uninstalledPs = null;
18870        PackageParser.Package pkg = null;
18871
18872        // for the uninstall-updates case and restricted profiles, remember the per-
18873        // user handle installed state
18874        int[] allUsers;
18875        synchronized (mPackages) {
18876            uninstalledPs = mSettings.mPackages.get(packageName);
18877            if (uninstalledPs == null) {
18878                Slog.w(TAG, "Not removing non-existent package " + packageName);
18879                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18880            }
18881
18882            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
18883                    && uninstalledPs.versionCode != versionCode) {
18884                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
18885                        + uninstalledPs.versionCode + " != " + versionCode);
18886                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18887            }
18888
18889            // Static shared libs can be declared by any package, so let us not
18890            // allow removing a package if it provides a lib others depend on.
18891            pkg = mPackages.get(packageName);
18892
18893            allUsers = sUserManager.getUserIds();
18894
18895            if (pkg != null && pkg.staticSharedLibName != null) {
18896                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
18897                        pkg.staticSharedLibVersion);
18898                if (libEntry != null) {
18899                    for (int currUserId : allUsers) {
18900                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
18901                            continue;
18902                        }
18903                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
18904                                libEntry.info, 0, currUserId);
18905                        if (!ArrayUtils.isEmpty(libClientPackages)) {
18906                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
18907                                    + " hosting lib " + libEntry.info.getName() + " version "
18908                                    + libEntry.info.getVersion() + " used by " + libClientPackages
18909                                    + " for user " + currUserId);
18910                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
18911                        }
18912                    }
18913                }
18914            }
18915
18916            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
18917        }
18918
18919        final int freezeUser;
18920        if (isUpdatedSystemApp(uninstalledPs)
18921                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
18922            // We're downgrading a system app, which will apply to all users, so
18923            // freeze them all during the downgrade
18924            freezeUser = UserHandle.USER_ALL;
18925        } else {
18926            freezeUser = removeUser;
18927        }
18928
18929        synchronized (mInstallLock) {
18930            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
18931            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
18932                    deleteFlags, "deletePackageX")) {
18933                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
18934                        deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
18935            }
18936            synchronized (mPackages) {
18937                if (res) {
18938                    if (pkg != null) {
18939                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
18940                    }
18941                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
18942                    updateInstantAppInstallerLocked(packageName);
18943                }
18944            }
18945        }
18946
18947        if (res) {
18948            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
18949            info.sendPackageRemovedBroadcasts(killApp);
18950            info.sendSystemPackageUpdatedBroadcasts();
18951            info.sendSystemPackageAppearedBroadcasts();
18952        }
18953        // Force a gc here.
18954        Runtime.getRuntime().gc();
18955        // Delete the resources here after sending the broadcast to let
18956        // other processes clean up before deleting resources.
18957        if (info.args != null) {
18958            synchronized (mInstallLock) {
18959                info.args.doPostDeleteLI(true);
18960            }
18961        }
18962
18963        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18964    }
18965
18966    static class PackageRemovedInfo {
18967        final PackageSender packageSender;
18968        String removedPackage;
18969        String installerPackageName;
18970        int uid = -1;
18971        int removedAppId = -1;
18972        int[] origUsers;
18973        int[] removedUsers = null;
18974        int[] broadcastUsers = null;
18975        SparseArray<Integer> installReasons;
18976        boolean isRemovedPackageSystemUpdate = false;
18977        boolean isUpdate;
18978        boolean dataRemoved;
18979        boolean removedForAllUsers;
18980        boolean isStaticSharedLib;
18981        // Clean up resources deleted packages.
18982        InstallArgs args = null;
18983        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
18984        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
18985
18986        PackageRemovedInfo(PackageSender packageSender) {
18987            this.packageSender = packageSender;
18988        }
18989
18990        void sendPackageRemovedBroadcasts(boolean killApp) {
18991            sendPackageRemovedBroadcastInternal(killApp);
18992            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
18993            for (int i = 0; i < childCount; i++) {
18994                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18995                childInfo.sendPackageRemovedBroadcastInternal(killApp);
18996            }
18997        }
18998
18999        void sendSystemPackageUpdatedBroadcasts() {
19000            if (isRemovedPackageSystemUpdate) {
19001                sendSystemPackageUpdatedBroadcastsInternal();
19002                final int childCount = (removedChildPackages != null)
19003                        ? removedChildPackages.size() : 0;
19004                for (int i = 0; i < childCount; i++) {
19005                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
19006                    if (childInfo.isRemovedPackageSystemUpdate) {
19007                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
19008                    }
19009                }
19010            }
19011        }
19012
19013        void sendSystemPackageAppearedBroadcasts() {
19014            final int packageCount = (appearedChildPackages != null)
19015                    ? appearedChildPackages.size() : 0;
19016            for (int i = 0; i < packageCount; i++) {
19017                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
19018                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
19019                    true, UserHandle.getAppId(installedInfo.uid),
19020                    installedInfo.newUsers);
19021            }
19022        }
19023
19024        private void sendSystemPackageUpdatedBroadcastsInternal() {
19025            Bundle extras = new Bundle(2);
19026            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
19027            extras.putBoolean(Intent.EXTRA_REPLACING, true);
19028            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
19029                removedPackage, extras, 0, null /*targetPackage*/, null, null);
19030            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
19031                removedPackage, extras, 0, null /*targetPackage*/, null, null);
19032            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
19033                null, null, 0, removedPackage, null, null);
19034            if (installerPackageName != null) {
19035                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
19036                        removedPackage, extras, 0 /*flags*/,
19037                        installerPackageName, null, null);
19038                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
19039                        removedPackage, extras, 0 /*flags*/,
19040                        installerPackageName, null, null);
19041            }
19042        }
19043
19044        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
19045            // Don't send static shared library removal broadcasts as these
19046            // libs are visible only the the apps that depend on them an one
19047            // cannot remove the library if it has a dependency.
19048            if (isStaticSharedLib) {
19049                return;
19050            }
19051            Bundle extras = new Bundle(2);
19052            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
19053            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
19054            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
19055            if (isUpdate || isRemovedPackageSystemUpdate) {
19056                extras.putBoolean(Intent.EXTRA_REPLACING, true);
19057            }
19058            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
19059            if (removedPackage != null) {
19060                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
19061                    removedPackage, extras, 0, null /*targetPackage*/, null, broadcastUsers);
19062                if (installerPackageName != null) {
19063                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
19064                            removedPackage, extras, 0 /*flags*/,
19065                            installerPackageName, null, broadcastUsers);
19066                }
19067                if (dataRemoved && !isRemovedPackageSystemUpdate) {
19068                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
19069                        removedPackage, extras,
19070                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
19071                        null, null, broadcastUsers);
19072                }
19073            }
19074            if (removedAppId >= 0) {
19075                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
19076                    null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
19077                    null, null, broadcastUsers);
19078            }
19079        }
19080
19081        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
19082            removedUsers = userIds;
19083            if (removedUsers == null) {
19084                broadcastUsers = null;
19085                return;
19086            }
19087
19088            broadcastUsers = EMPTY_INT_ARRAY;
19089            for (int i = userIds.length - 1; i >= 0; --i) {
19090                final int userId = userIds[i];
19091                if (deletedPackageSetting.getInstantApp(userId)) {
19092                    continue;
19093                }
19094                broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
19095            }
19096        }
19097    }
19098
19099    /*
19100     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
19101     * flag is not set, the data directory is removed as well.
19102     * make sure this flag is set for partially installed apps. If not its meaningless to
19103     * delete a partially installed application.
19104     */
19105    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
19106            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
19107        String packageName = ps.name;
19108        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
19109        // Retrieve object to delete permissions for shared user later on
19110        final PackageParser.Package deletedPkg;
19111        final PackageSetting deletedPs;
19112        // reader
19113        synchronized (mPackages) {
19114            deletedPkg = mPackages.get(packageName);
19115            deletedPs = mSettings.mPackages.get(packageName);
19116            if (outInfo != null) {
19117                outInfo.removedPackage = packageName;
19118                outInfo.installerPackageName = ps.installerPackageName;
19119                outInfo.isStaticSharedLib = deletedPkg != null
19120                        && deletedPkg.staticSharedLibName != null;
19121                outInfo.populateUsers(deletedPs == null ? null
19122                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
19123            }
19124        }
19125
19126        removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
19127
19128        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
19129            final PackageParser.Package resolvedPkg;
19130            if (deletedPkg != null) {
19131                resolvedPkg = deletedPkg;
19132            } else {
19133                // We don't have a parsed package when it lives on an ejected
19134                // adopted storage device, so fake something together
19135                resolvedPkg = new PackageParser.Package(ps.name);
19136                resolvedPkg.setVolumeUuid(ps.volumeUuid);
19137            }
19138            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
19139                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19140            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
19141            if (outInfo != null) {
19142                outInfo.dataRemoved = true;
19143            }
19144            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
19145        }
19146
19147        int removedAppId = -1;
19148
19149        // writer
19150        synchronized (mPackages) {
19151            boolean installedStateChanged = false;
19152            if (deletedPs != null) {
19153                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
19154                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
19155                    clearDefaultBrowserIfNeeded(packageName);
19156                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
19157                    removedAppId = mSettings.removePackageLPw(packageName);
19158                    if (outInfo != null) {
19159                        outInfo.removedAppId = removedAppId;
19160                    }
19161                    updatePermissionsLPw(deletedPs.name, null, 0);
19162                    if (deletedPs.sharedUser != null) {
19163                        // Remove permissions associated with package. Since runtime
19164                        // permissions are per user we have to kill the removed package
19165                        // or packages running under the shared user of the removed
19166                        // package if revoking the permissions requested only by the removed
19167                        // package is successful and this causes a change in gids.
19168                        for (int userId : UserManagerService.getInstance().getUserIds()) {
19169                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
19170                                    userId);
19171                            if (userIdToKill == UserHandle.USER_ALL
19172                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
19173                                // If gids changed for this user, kill all affected packages.
19174                                mHandler.post(new Runnable() {
19175                                    @Override
19176                                    public void run() {
19177                                        // This has to happen with no lock held.
19178                                        killApplication(deletedPs.name, deletedPs.appId,
19179                                                KILL_APP_REASON_GIDS_CHANGED);
19180                                    }
19181                                });
19182                                break;
19183                            }
19184                        }
19185                    }
19186                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
19187                }
19188                // make sure to preserve per-user disabled state if this removal was just
19189                // a downgrade of a system app to the factory package
19190                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
19191                    if (DEBUG_REMOVE) {
19192                        Slog.d(TAG, "Propagating install state across downgrade");
19193                    }
19194                    for (int userId : allUserHandles) {
19195                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
19196                        if (DEBUG_REMOVE) {
19197                            Slog.d(TAG, "    user " + userId + " => " + installed);
19198                        }
19199                        if (installed != ps.getInstalled(userId)) {
19200                            installedStateChanged = true;
19201                        }
19202                        ps.setInstalled(installed, userId);
19203                    }
19204                }
19205            }
19206            // can downgrade to reader
19207            if (writeSettings) {
19208                // Save settings now
19209                mSettings.writeLPr();
19210            }
19211            if (installedStateChanged) {
19212                mSettings.writeKernelMappingLPr(ps);
19213            }
19214        }
19215        if (removedAppId != -1) {
19216            // A user ID was deleted here. Go through all users and remove it
19217            // from KeyStore.
19218            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
19219        }
19220    }
19221
19222    static boolean locationIsPrivileged(File path) {
19223        try {
19224            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
19225                    .getCanonicalPath();
19226            return path.getCanonicalPath().startsWith(privilegedAppDir);
19227        } catch (IOException e) {
19228            Slog.e(TAG, "Unable to access code path " + path);
19229        }
19230        return false;
19231    }
19232
19233    /*
19234     * Tries to delete system package.
19235     */
19236    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
19237            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
19238            boolean writeSettings) {
19239        if (deletedPs.parentPackageName != null) {
19240            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
19241            return false;
19242        }
19243
19244        final boolean applyUserRestrictions
19245                = (allUserHandles != null) && (outInfo.origUsers != null);
19246        final PackageSetting disabledPs;
19247        // Confirm if the system package has been updated
19248        // An updated system app can be deleted. This will also have to restore
19249        // the system pkg from system partition
19250        // reader
19251        synchronized (mPackages) {
19252            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
19253        }
19254
19255        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
19256                + " disabledPs=" + disabledPs);
19257
19258        if (disabledPs == null) {
19259            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
19260            return false;
19261        } else if (DEBUG_REMOVE) {
19262            Slog.d(TAG, "Deleting system pkg from data partition");
19263        }
19264
19265        if (DEBUG_REMOVE) {
19266            if (applyUserRestrictions) {
19267                Slog.d(TAG, "Remembering install states:");
19268                for (int userId : allUserHandles) {
19269                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
19270                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
19271                }
19272            }
19273        }
19274
19275        // Delete the updated package
19276        outInfo.isRemovedPackageSystemUpdate = true;
19277        if (outInfo.removedChildPackages != null) {
19278            final int childCount = (deletedPs.childPackageNames != null)
19279                    ? deletedPs.childPackageNames.size() : 0;
19280            for (int i = 0; i < childCount; i++) {
19281                String childPackageName = deletedPs.childPackageNames.get(i);
19282                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
19283                        .contains(childPackageName)) {
19284                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19285                            childPackageName);
19286                    if (childInfo != null) {
19287                        childInfo.isRemovedPackageSystemUpdate = true;
19288                    }
19289                }
19290            }
19291        }
19292
19293        if (disabledPs.versionCode < deletedPs.versionCode) {
19294            // Delete data for downgrades
19295            flags &= ~PackageManager.DELETE_KEEP_DATA;
19296        } else {
19297            // Preserve data by setting flag
19298            flags |= PackageManager.DELETE_KEEP_DATA;
19299        }
19300
19301        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
19302                outInfo, writeSettings, disabledPs.pkg);
19303        if (!ret) {
19304            return false;
19305        }
19306
19307        // writer
19308        synchronized (mPackages) {
19309            // Reinstate the old system package
19310            enableSystemPackageLPw(disabledPs.pkg);
19311            // Remove any native libraries from the upgraded package.
19312            removeNativeBinariesLI(deletedPs);
19313        }
19314
19315        // Install the system package
19316        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
19317        int parseFlags = mDefParseFlags
19318                | PackageParser.PARSE_MUST_BE_APK
19319                | PackageParser.PARSE_IS_SYSTEM
19320                | PackageParser.PARSE_IS_SYSTEM_DIR;
19321        if (locationIsPrivileged(disabledPs.codePath)) {
19322            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
19323        }
19324
19325        final PackageParser.Package newPkg;
19326        try {
19327            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */,
19328                0 /* currentTime */, null);
19329        } catch (PackageManagerException e) {
19330            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
19331                    + e.getMessage());
19332            return false;
19333        }
19334
19335        try {
19336            // update shared libraries for the newly re-installed system package
19337            updateSharedLibrariesLPr(newPkg, null);
19338        } catch (PackageManagerException e) {
19339            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
19340        }
19341
19342        prepareAppDataAfterInstallLIF(newPkg);
19343
19344        // writer
19345        synchronized (mPackages) {
19346            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
19347
19348            // Propagate the permissions state as we do not want to drop on the floor
19349            // runtime permissions. The update permissions method below will take
19350            // care of removing obsolete permissions and grant install permissions.
19351            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
19352            updatePermissionsLPw(newPkg.packageName, newPkg,
19353                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
19354
19355            if (applyUserRestrictions) {
19356                boolean installedStateChanged = false;
19357                if (DEBUG_REMOVE) {
19358                    Slog.d(TAG, "Propagating install state across reinstall");
19359                }
19360                for (int userId : allUserHandles) {
19361                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
19362                    if (DEBUG_REMOVE) {
19363                        Slog.d(TAG, "    user " + userId + " => " + installed);
19364                    }
19365                    if (installed != ps.getInstalled(userId)) {
19366                        installedStateChanged = true;
19367                    }
19368                    ps.setInstalled(installed, userId);
19369
19370                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19371                }
19372                // Regardless of writeSettings we need to ensure that this restriction
19373                // state propagation is persisted
19374                mSettings.writeAllUsersPackageRestrictionsLPr();
19375                if (installedStateChanged) {
19376                    mSettings.writeKernelMappingLPr(ps);
19377                }
19378            }
19379            // can downgrade to reader here
19380            if (writeSettings) {
19381                mSettings.writeLPr();
19382            }
19383        }
19384        return true;
19385    }
19386
19387    private boolean deleteInstalledPackageLIF(PackageSetting ps,
19388            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
19389            PackageRemovedInfo outInfo, boolean writeSettings,
19390            PackageParser.Package replacingPackage) {
19391        synchronized (mPackages) {
19392            if (outInfo != null) {
19393                outInfo.uid = ps.appId;
19394            }
19395
19396            if (outInfo != null && outInfo.removedChildPackages != null) {
19397                final int childCount = (ps.childPackageNames != null)
19398                        ? ps.childPackageNames.size() : 0;
19399                for (int i = 0; i < childCount; i++) {
19400                    String childPackageName = ps.childPackageNames.get(i);
19401                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
19402                    if (childPs == null) {
19403                        return false;
19404                    }
19405                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19406                            childPackageName);
19407                    if (childInfo != null) {
19408                        childInfo.uid = childPs.appId;
19409                    }
19410                }
19411            }
19412        }
19413
19414        // Delete package data from internal structures and also remove data if flag is set
19415        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
19416
19417        // Delete the child packages data
19418        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
19419        for (int i = 0; i < childCount; i++) {
19420            PackageSetting childPs;
19421            synchronized (mPackages) {
19422                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
19423            }
19424            if (childPs != null) {
19425                PackageRemovedInfo childOutInfo = (outInfo != null
19426                        && outInfo.removedChildPackages != null)
19427                        ? outInfo.removedChildPackages.get(childPs.name) : null;
19428                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
19429                        && (replacingPackage != null
19430                        && !replacingPackage.hasChildPackage(childPs.name))
19431                        ? flags & ~DELETE_KEEP_DATA : flags;
19432                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
19433                        deleteFlags, writeSettings);
19434            }
19435        }
19436
19437        // Delete application code and resources only for parent packages
19438        if (ps.parentPackageName == null) {
19439            if (deleteCodeAndResources && (outInfo != null)) {
19440                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
19441                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
19442                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
19443            }
19444        }
19445
19446        return true;
19447    }
19448
19449    @Override
19450    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
19451            int userId) {
19452        mContext.enforceCallingOrSelfPermission(
19453                android.Manifest.permission.DELETE_PACKAGES, null);
19454        synchronized (mPackages) {
19455            // Cannot block uninstall of static shared libs as they are
19456            // considered a part of the using app (emulating static linking).
19457            // Also static libs are installed always on internal storage.
19458            PackageParser.Package pkg = mPackages.get(packageName);
19459            if (pkg != null && pkg.staticSharedLibName != null) {
19460                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
19461                        + " providing static shared library: " + pkg.staticSharedLibName);
19462                return false;
19463            }
19464            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
19465            mSettings.writePackageRestrictionsLPr(userId);
19466        }
19467        return true;
19468    }
19469
19470    @Override
19471    public boolean getBlockUninstallForUser(String packageName, int userId) {
19472        synchronized (mPackages) {
19473            final PackageSetting ps = mSettings.mPackages.get(packageName);
19474            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
19475                return false;
19476            }
19477            return mSettings.getBlockUninstallLPr(userId, packageName);
19478        }
19479    }
19480
19481    @Override
19482    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
19483        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
19484        synchronized (mPackages) {
19485            PackageSetting ps = mSettings.mPackages.get(packageName);
19486            if (ps == null) {
19487                Log.w(TAG, "Package doesn't exist: " + packageName);
19488                return false;
19489            }
19490            if (systemUserApp) {
19491                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
19492            } else {
19493                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
19494            }
19495            mSettings.writeLPr();
19496        }
19497        return true;
19498    }
19499
19500    /*
19501     * This method handles package deletion in general
19502     */
19503    private boolean deletePackageLIF(String packageName, UserHandle user,
19504            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
19505            PackageRemovedInfo outInfo, boolean writeSettings,
19506            PackageParser.Package replacingPackage) {
19507        if (packageName == null) {
19508            Slog.w(TAG, "Attempt to delete null packageName.");
19509            return false;
19510        }
19511
19512        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
19513
19514        PackageSetting ps;
19515        synchronized (mPackages) {
19516            ps = mSettings.mPackages.get(packageName);
19517            if (ps == null) {
19518                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19519                return false;
19520            }
19521
19522            if (ps.parentPackageName != null && (!isSystemApp(ps)
19523                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
19524                if (DEBUG_REMOVE) {
19525                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
19526                            + ((user == null) ? UserHandle.USER_ALL : user));
19527                }
19528                final int removedUserId = (user != null) ? user.getIdentifier()
19529                        : UserHandle.USER_ALL;
19530                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
19531                    return false;
19532                }
19533                markPackageUninstalledForUserLPw(ps, user);
19534                scheduleWritePackageRestrictionsLocked(user);
19535                return true;
19536            }
19537        }
19538
19539        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
19540                && user.getIdentifier() != UserHandle.USER_ALL)) {
19541            // The caller is asking that the package only be deleted for a single
19542            // user.  To do this, we just mark its uninstalled state and delete
19543            // its data. If this is a system app, we only allow this to happen if
19544            // they have set the special DELETE_SYSTEM_APP which requests different
19545            // semantics than normal for uninstalling system apps.
19546            markPackageUninstalledForUserLPw(ps, user);
19547
19548            if (!isSystemApp(ps)) {
19549                // Do not uninstall the APK if an app should be cached
19550                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
19551                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
19552                    // Other user still have this package installed, so all
19553                    // we need to do is clear this user's data and save that
19554                    // it is uninstalled.
19555                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
19556                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
19557                        return false;
19558                    }
19559                    scheduleWritePackageRestrictionsLocked(user);
19560                    return true;
19561                } else {
19562                    // We need to set it back to 'installed' so the uninstall
19563                    // broadcasts will be sent correctly.
19564                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
19565                    ps.setInstalled(true, user.getIdentifier());
19566                    mSettings.writeKernelMappingLPr(ps);
19567                }
19568            } else {
19569                // This is a system app, so we assume that the
19570                // other users still have this package installed, so all
19571                // we need to do is clear this user's data and save that
19572                // it is uninstalled.
19573                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
19574                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
19575                    return false;
19576                }
19577                scheduleWritePackageRestrictionsLocked(user);
19578                return true;
19579            }
19580        }
19581
19582        // If we are deleting a composite package for all users, keep track
19583        // of result for each child.
19584        if (ps.childPackageNames != null && outInfo != null) {
19585            synchronized (mPackages) {
19586                final int childCount = ps.childPackageNames.size();
19587                outInfo.removedChildPackages = new ArrayMap<>(childCount);
19588                for (int i = 0; i < childCount; i++) {
19589                    String childPackageName = ps.childPackageNames.get(i);
19590                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
19591                    childInfo.removedPackage = childPackageName;
19592                    childInfo.installerPackageName = ps.installerPackageName;
19593                    outInfo.removedChildPackages.put(childPackageName, childInfo);
19594                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
19595                    if (childPs != null) {
19596                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
19597                    }
19598                }
19599            }
19600        }
19601
19602        boolean ret = false;
19603        if (isSystemApp(ps)) {
19604            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
19605            // When an updated system application is deleted we delete the existing resources
19606            // as well and fall back to existing code in system partition
19607            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
19608        } else {
19609            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
19610            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
19611                    outInfo, writeSettings, replacingPackage);
19612        }
19613
19614        // Take a note whether we deleted the package for all users
19615        if (outInfo != null) {
19616            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
19617            if (outInfo.removedChildPackages != null) {
19618                synchronized (mPackages) {
19619                    final int childCount = outInfo.removedChildPackages.size();
19620                    for (int i = 0; i < childCount; i++) {
19621                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
19622                        if (childInfo != null) {
19623                            childInfo.removedForAllUsers = mPackages.get(
19624                                    childInfo.removedPackage) == null;
19625                        }
19626                    }
19627                }
19628            }
19629            // If we uninstalled an update to a system app there may be some
19630            // child packages that appeared as they are declared in the system
19631            // app but were not declared in the update.
19632            if (isSystemApp(ps)) {
19633                synchronized (mPackages) {
19634                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
19635                    final int childCount = (updatedPs.childPackageNames != null)
19636                            ? updatedPs.childPackageNames.size() : 0;
19637                    for (int i = 0; i < childCount; i++) {
19638                        String childPackageName = updatedPs.childPackageNames.get(i);
19639                        if (outInfo.removedChildPackages == null
19640                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
19641                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
19642                            if (childPs == null) {
19643                                continue;
19644                            }
19645                            PackageInstalledInfo installRes = new PackageInstalledInfo();
19646                            installRes.name = childPackageName;
19647                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
19648                            installRes.pkg = mPackages.get(childPackageName);
19649                            installRes.uid = childPs.pkg.applicationInfo.uid;
19650                            if (outInfo.appearedChildPackages == null) {
19651                                outInfo.appearedChildPackages = new ArrayMap<>();
19652                            }
19653                            outInfo.appearedChildPackages.put(childPackageName, installRes);
19654                        }
19655                    }
19656                }
19657            }
19658        }
19659
19660        return ret;
19661    }
19662
19663    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
19664        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
19665                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
19666        for (int nextUserId : userIds) {
19667            if (DEBUG_REMOVE) {
19668                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
19669            }
19670            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
19671                    false /*installed*/,
19672                    true /*stopped*/,
19673                    true /*notLaunched*/,
19674                    false /*hidden*/,
19675                    false /*suspended*/,
19676                    false /*instantApp*/,
19677                    null /*lastDisableAppCaller*/,
19678                    null /*enabledComponents*/,
19679                    null /*disabledComponents*/,
19680                    ps.readUserState(nextUserId).domainVerificationStatus,
19681                    0, PackageManager.INSTALL_REASON_UNKNOWN);
19682        }
19683        mSettings.writeKernelMappingLPr(ps);
19684    }
19685
19686    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
19687            PackageRemovedInfo outInfo) {
19688        final PackageParser.Package pkg;
19689        synchronized (mPackages) {
19690            pkg = mPackages.get(ps.name);
19691        }
19692
19693        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
19694                : new int[] {userId};
19695        for (int nextUserId : userIds) {
19696            if (DEBUG_REMOVE) {
19697                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
19698                        + nextUserId);
19699            }
19700
19701            destroyAppDataLIF(pkg, userId,
19702                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19703            destroyAppProfilesLIF(pkg, userId);
19704            clearDefaultBrowserIfNeededForUser(ps.name, userId);
19705            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
19706            schedulePackageCleaning(ps.name, nextUserId, false);
19707            synchronized (mPackages) {
19708                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
19709                    scheduleWritePackageRestrictionsLocked(nextUserId);
19710                }
19711                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
19712            }
19713        }
19714
19715        if (outInfo != null) {
19716            outInfo.removedPackage = ps.name;
19717            outInfo.installerPackageName = ps.installerPackageName;
19718            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
19719            outInfo.removedAppId = ps.appId;
19720            outInfo.removedUsers = userIds;
19721            outInfo.broadcastUsers = userIds;
19722        }
19723
19724        return true;
19725    }
19726
19727    private final class ClearStorageConnection implements ServiceConnection {
19728        IMediaContainerService mContainerService;
19729
19730        @Override
19731        public void onServiceConnected(ComponentName name, IBinder service) {
19732            synchronized (this) {
19733                mContainerService = IMediaContainerService.Stub
19734                        .asInterface(Binder.allowBlocking(service));
19735                notifyAll();
19736            }
19737        }
19738
19739        @Override
19740        public void onServiceDisconnected(ComponentName name) {
19741        }
19742    }
19743
19744    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
19745        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
19746
19747        final boolean mounted;
19748        if (Environment.isExternalStorageEmulated()) {
19749            mounted = true;
19750        } else {
19751            final String status = Environment.getExternalStorageState();
19752
19753            mounted = status.equals(Environment.MEDIA_MOUNTED)
19754                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
19755        }
19756
19757        if (!mounted) {
19758            return;
19759        }
19760
19761        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
19762        int[] users;
19763        if (userId == UserHandle.USER_ALL) {
19764            users = sUserManager.getUserIds();
19765        } else {
19766            users = new int[] { userId };
19767        }
19768        final ClearStorageConnection conn = new ClearStorageConnection();
19769        if (mContext.bindServiceAsUser(
19770                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
19771            try {
19772                for (int curUser : users) {
19773                    long timeout = SystemClock.uptimeMillis() + 5000;
19774                    synchronized (conn) {
19775                        long now;
19776                        while (conn.mContainerService == null &&
19777                                (now = SystemClock.uptimeMillis()) < timeout) {
19778                            try {
19779                                conn.wait(timeout - now);
19780                            } catch (InterruptedException e) {
19781                            }
19782                        }
19783                    }
19784                    if (conn.mContainerService == null) {
19785                        return;
19786                    }
19787
19788                    final UserEnvironment userEnv = new UserEnvironment(curUser);
19789                    clearDirectory(conn.mContainerService,
19790                            userEnv.buildExternalStorageAppCacheDirs(packageName));
19791                    if (allData) {
19792                        clearDirectory(conn.mContainerService,
19793                                userEnv.buildExternalStorageAppDataDirs(packageName));
19794                        clearDirectory(conn.mContainerService,
19795                                userEnv.buildExternalStorageAppMediaDirs(packageName));
19796                    }
19797                }
19798            } finally {
19799                mContext.unbindService(conn);
19800            }
19801        }
19802    }
19803
19804    @Override
19805    public void clearApplicationProfileData(String packageName) {
19806        enforceSystemOrRoot("Only the system can clear all profile data");
19807
19808        final PackageParser.Package pkg;
19809        synchronized (mPackages) {
19810            pkg = mPackages.get(packageName);
19811        }
19812
19813        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
19814            synchronized (mInstallLock) {
19815                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
19816            }
19817        }
19818    }
19819
19820    @Override
19821    public void clearApplicationUserData(final String packageName,
19822            final IPackageDataObserver observer, final int userId) {
19823        mContext.enforceCallingOrSelfPermission(
19824                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
19825
19826        final int callingUid = Binder.getCallingUid();
19827        enforceCrossUserPermission(callingUid, userId,
19828                true /* requireFullPermission */, false /* checkShell */, "clear application data");
19829
19830        final PackageSetting ps = mSettings.getPackageLPr(packageName);
19831        if (ps != null && filterAppAccessLPr(ps, callingUid, userId)) {
19832            return;
19833        }
19834        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
19835            throw new SecurityException("Cannot clear data for a protected package: "
19836                    + packageName);
19837        }
19838        // Queue up an async operation since the package deletion may take a little while.
19839        mHandler.post(new Runnable() {
19840            public void run() {
19841                mHandler.removeCallbacks(this);
19842                final boolean succeeded;
19843                try (PackageFreezer freezer = freezePackage(packageName,
19844                        "clearApplicationUserData")) {
19845                    synchronized (mInstallLock) {
19846                        succeeded = clearApplicationUserDataLIF(packageName, userId);
19847                    }
19848                    clearExternalStorageDataSync(packageName, userId, true);
19849                    synchronized (mPackages) {
19850                        mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
19851                                packageName, userId);
19852                    }
19853                }
19854                if (succeeded) {
19855                    // invoke DeviceStorageMonitor's update method to clear any notifications
19856                    DeviceStorageMonitorInternal dsm = LocalServices
19857                            .getService(DeviceStorageMonitorInternal.class);
19858                    if (dsm != null) {
19859                        dsm.checkMemory();
19860                    }
19861                }
19862                if(observer != null) {
19863                    try {
19864                        observer.onRemoveCompleted(packageName, succeeded);
19865                    } catch (RemoteException e) {
19866                        Log.i(TAG, "Observer no longer exists.");
19867                    }
19868                } //end if observer
19869            } //end run
19870        });
19871    }
19872
19873    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
19874        if (packageName == null) {
19875            Slog.w(TAG, "Attempt to delete null packageName.");
19876            return false;
19877        }
19878
19879        // Try finding details about the requested package
19880        PackageParser.Package pkg;
19881        synchronized (mPackages) {
19882            pkg = mPackages.get(packageName);
19883            if (pkg == null) {
19884                final PackageSetting ps = mSettings.mPackages.get(packageName);
19885                if (ps != null) {
19886                    pkg = ps.pkg;
19887                }
19888            }
19889
19890            if (pkg == null) {
19891                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19892                return false;
19893            }
19894
19895            PackageSetting ps = (PackageSetting) pkg.mExtras;
19896            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19897        }
19898
19899        clearAppDataLIF(pkg, userId,
19900                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19901
19902        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
19903        removeKeystoreDataIfNeeded(userId, appId);
19904
19905        UserManagerInternal umInternal = getUserManagerInternal();
19906        final int flags;
19907        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
19908            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19909        } else if (umInternal.isUserRunning(userId)) {
19910            flags = StorageManager.FLAG_STORAGE_DE;
19911        } else {
19912            flags = 0;
19913        }
19914        prepareAppDataContentsLIF(pkg, userId, flags);
19915
19916        return true;
19917    }
19918
19919    /**
19920     * Reverts user permission state changes (permissions and flags) in
19921     * all packages for a given user.
19922     *
19923     * @param userId The device user for which to do a reset.
19924     */
19925    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
19926        final int packageCount = mPackages.size();
19927        for (int i = 0; i < packageCount; i++) {
19928            PackageParser.Package pkg = mPackages.valueAt(i);
19929            PackageSetting ps = (PackageSetting) pkg.mExtras;
19930            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19931        }
19932    }
19933
19934    private void resetNetworkPolicies(int userId) {
19935        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
19936    }
19937
19938    /**
19939     * Reverts user permission state changes (permissions and flags).
19940     *
19941     * @param ps The package for which to reset.
19942     * @param userId The device user for which to do a reset.
19943     */
19944    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
19945            final PackageSetting ps, final int userId) {
19946        if (ps.pkg == null) {
19947            return;
19948        }
19949
19950        // These are flags that can change base on user actions.
19951        final int userSettableMask = FLAG_PERMISSION_USER_SET
19952                | FLAG_PERMISSION_USER_FIXED
19953                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
19954                | FLAG_PERMISSION_REVIEW_REQUIRED;
19955
19956        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
19957                | FLAG_PERMISSION_POLICY_FIXED;
19958
19959        boolean writeInstallPermissions = false;
19960        boolean writeRuntimePermissions = false;
19961
19962        final int permissionCount = ps.pkg.requestedPermissions.size();
19963        for (int i = 0; i < permissionCount; i++) {
19964            String permission = ps.pkg.requestedPermissions.get(i);
19965
19966            BasePermission bp = mSettings.mPermissions.get(permission);
19967            if (bp == null) {
19968                continue;
19969            }
19970
19971            // If shared user we just reset the state to which only this app contributed.
19972            if (ps.sharedUser != null) {
19973                boolean used = false;
19974                final int packageCount = ps.sharedUser.packages.size();
19975                for (int j = 0; j < packageCount; j++) {
19976                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
19977                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
19978                            && pkg.pkg.requestedPermissions.contains(permission)) {
19979                        used = true;
19980                        break;
19981                    }
19982                }
19983                if (used) {
19984                    continue;
19985                }
19986            }
19987
19988            PermissionsState permissionsState = ps.getPermissionsState();
19989
19990            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
19991
19992            // Always clear the user settable flags.
19993            final boolean hasInstallState = permissionsState.getInstallPermissionState(
19994                    bp.name) != null;
19995            // If permission review is enabled and this is a legacy app, mark the
19996            // permission as requiring a review as this is the initial state.
19997            int flags = 0;
19998            if (mPermissionReviewRequired
19999                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
20000                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
20001            }
20002            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
20003                if (hasInstallState) {
20004                    writeInstallPermissions = true;
20005                } else {
20006                    writeRuntimePermissions = true;
20007                }
20008            }
20009
20010            // Below is only runtime permission handling.
20011            if (!bp.isRuntime()) {
20012                continue;
20013            }
20014
20015            // Never clobber system or policy.
20016            if ((oldFlags & policyOrSystemFlags) != 0) {
20017                continue;
20018            }
20019
20020            // If this permission was granted by default, make sure it is.
20021            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
20022                if (permissionsState.grantRuntimePermission(bp, userId)
20023                        != PERMISSION_OPERATION_FAILURE) {
20024                    writeRuntimePermissions = true;
20025                }
20026            // If permission review is enabled the permissions for a legacy apps
20027            // are represented as constantly granted runtime ones, so don't revoke.
20028            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
20029                // Otherwise, reset the permission.
20030                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
20031                switch (revokeResult) {
20032                    case PERMISSION_OPERATION_SUCCESS:
20033                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
20034                        writeRuntimePermissions = true;
20035                        final int appId = ps.appId;
20036                        mHandler.post(new Runnable() {
20037                            @Override
20038                            public void run() {
20039                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
20040                            }
20041                        });
20042                    } break;
20043                }
20044            }
20045        }
20046
20047        // Synchronously write as we are taking permissions away.
20048        if (writeRuntimePermissions) {
20049            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
20050        }
20051
20052        // Synchronously write as we are taking permissions away.
20053        if (writeInstallPermissions) {
20054            mSettings.writeLPr();
20055        }
20056    }
20057
20058    /**
20059     * Remove entries from the keystore daemon. Will only remove it if the
20060     * {@code appId} is valid.
20061     */
20062    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
20063        if (appId < 0) {
20064            return;
20065        }
20066
20067        final KeyStore keyStore = KeyStore.getInstance();
20068        if (keyStore != null) {
20069            if (userId == UserHandle.USER_ALL) {
20070                for (final int individual : sUserManager.getUserIds()) {
20071                    keyStore.clearUid(UserHandle.getUid(individual, appId));
20072                }
20073            } else {
20074                keyStore.clearUid(UserHandle.getUid(userId, appId));
20075            }
20076        } else {
20077            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
20078        }
20079    }
20080
20081    @Override
20082    public void deleteApplicationCacheFiles(final String packageName,
20083            final IPackageDataObserver observer) {
20084        final int userId = UserHandle.getCallingUserId();
20085        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
20086    }
20087
20088    @Override
20089    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
20090            final IPackageDataObserver observer) {
20091        final int callingUid = Binder.getCallingUid();
20092        mContext.enforceCallingOrSelfPermission(
20093                android.Manifest.permission.DELETE_CACHE_FILES, null);
20094        enforceCrossUserPermission(callingUid, userId,
20095                /* requireFullPermission= */ true, /* checkShell= */ false,
20096                "delete application cache files");
20097        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
20098                android.Manifest.permission.ACCESS_INSTANT_APPS);
20099
20100        final PackageParser.Package pkg;
20101        synchronized (mPackages) {
20102            pkg = mPackages.get(packageName);
20103        }
20104
20105        // Queue up an async operation since the package deletion may take a little while.
20106        mHandler.post(new Runnable() {
20107            public void run() {
20108                final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
20109                boolean doClearData = true;
20110                if (ps != null) {
20111                    final boolean targetIsInstantApp =
20112                            ps.getInstantApp(UserHandle.getUserId(callingUid));
20113                    doClearData = !targetIsInstantApp
20114                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
20115                }
20116                if (doClearData) {
20117                    synchronized (mInstallLock) {
20118                        final int flags = StorageManager.FLAG_STORAGE_DE
20119                                | StorageManager.FLAG_STORAGE_CE;
20120                        // We're only clearing cache files, so we don't care if the
20121                        // app is unfrozen and still able to run
20122                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
20123                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20124                    }
20125                    clearExternalStorageDataSync(packageName, userId, false);
20126                }
20127                if (observer != null) {
20128                    try {
20129                        observer.onRemoveCompleted(packageName, true);
20130                    } catch (RemoteException e) {
20131                        Log.i(TAG, "Observer no longer exists.");
20132                    }
20133                }
20134            }
20135        });
20136    }
20137
20138    @Override
20139    public void getPackageSizeInfo(final String packageName, int userHandle,
20140            final IPackageStatsObserver observer) {
20141        throw new UnsupportedOperationException(
20142                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
20143    }
20144
20145    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
20146        final PackageSetting ps;
20147        synchronized (mPackages) {
20148            ps = mSettings.mPackages.get(packageName);
20149            if (ps == null) {
20150                Slog.w(TAG, "Failed to find settings for " + packageName);
20151                return false;
20152            }
20153        }
20154
20155        final String[] packageNames = { packageName };
20156        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
20157        final String[] codePaths = { ps.codePathString };
20158
20159        try {
20160            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
20161                    ps.appId, ceDataInodes, codePaths, stats);
20162
20163            // For now, ignore code size of packages on system partition
20164            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
20165                stats.codeSize = 0;
20166            }
20167
20168            // External clients expect these to be tracked separately
20169            stats.dataSize -= stats.cacheSize;
20170
20171        } catch (InstallerException e) {
20172            Slog.w(TAG, String.valueOf(e));
20173            return false;
20174        }
20175
20176        return true;
20177    }
20178
20179    private int getUidTargetSdkVersionLockedLPr(int uid) {
20180        Object obj = mSettings.getUserIdLPr(uid);
20181        if (obj instanceof SharedUserSetting) {
20182            final SharedUserSetting sus = (SharedUserSetting) obj;
20183            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
20184            final Iterator<PackageSetting> it = sus.packages.iterator();
20185            while (it.hasNext()) {
20186                final PackageSetting ps = it.next();
20187                if (ps.pkg != null) {
20188                    int v = ps.pkg.applicationInfo.targetSdkVersion;
20189                    if (v < vers) vers = v;
20190                }
20191            }
20192            return vers;
20193        } else if (obj instanceof PackageSetting) {
20194            final PackageSetting ps = (PackageSetting) obj;
20195            if (ps.pkg != null) {
20196                return ps.pkg.applicationInfo.targetSdkVersion;
20197            }
20198        }
20199        return Build.VERSION_CODES.CUR_DEVELOPMENT;
20200    }
20201
20202    @Override
20203    public void addPreferredActivity(IntentFilter filter, int match,
20204            ComponentName[] set, ComponentName activity, int userId) {
20205        addPreferredActivityInternal(filter, match, set, activity, true, userId,
20206                "Adding preferred");
20207    }
20208
20209    private void addPreferredActivityInternal(IntentFilter filter, int match,
20210            ComponentName[] set, ComponentName activity, boolean always, int userId,
20211            String opname) {
20212        // writer
20213        int callingUid = Binder.getCallingUid();
20214        enforceCrossUserPermission(callingUid, userId,
20215                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
20216        if (filter.countActions() == 0) {
20217            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20218            return;
20219        }
20220        synchronized (mPackages) {
20221            if (mContext.checkCallingOrSelfPermission(
20222                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20223                    != PackageManager.PERMISSION_GRANTED) {
20224                if (getUidTargetSdkVersionLockedLPr(callingUid)
20225                        < Build.VERSION_CODES.FROYO) {
20226                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
20227                            + callingUid);
20228                    return;
20229                }
20230                mContext.enforceCallingOrSelfPermission(
20231                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20232            }
20233
20234            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
20235            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
20236                    + userId + ":");
20237            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20238            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
20239            scheduleWritePackageRestrictionsLocked(userId);
20240            postPreferredActivityChangedBroadcast(userId);
20241        }
20242    }
20243
20244    private void postPreferredActivityChangedBroadcast(int userId) {
20245        mHandler.post(() -> {
20246            final IActivityManager am = ActivityManager.getService();
20247            if (am == null) {
20248                return;
20249            }
20250
20251            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
20252            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
20253            try {
20254                am.broadcastIntent(null, intent, null, null,
20255                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
20256                        null, false, false, userId);
20257            } catch (RemoteException e) {
20258            }
20259        });
20260    }
20261
20262    @Override
20263    public void replacePreferredActivity(IntentFilter filter, int match,
20264            ComponentName[] set, ComponentName activity, int userId) {
20265        if (filter.countActions() != 1) {
20266            throw new IllegalArgumentException(
20267                    "replacePreferredActivity expects filter to have only 1 action.");
20268        }
20269        if (filter.countDataAuthorities() != 0
20270                || filter.countDataPaths() != 0
20271                || filter.countDataSchemes() > 1
20272                || filter.countDataTypes() != 0) {
20273            throw new IllegalArgumentException(
20274                    "replacePreferredActivity expects filter to have no data authorities, " +
20275                    "paths, or types; and at most one scheme.");
20276        }
20277
20278        final int callingUid = Binder.getCallingUid();
20279        enforceCrossUserPermission(callingUid, userId,
20280                true /* requireFullPermission */, false /* checkShell */,
20281                "replace preferred activity");
20282        synchronized (mPackages) {
20283            if (mContext.checkCallingOrSelfPermission(
20284                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20285                    != PackageManager.PERMISSION_GRANTED) {
20286                if (getUidTargetSdkVersionLockedLPr(callingUid)
20287                        < Build.VERSION_CODES.FROYO) {
20288                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
20289                            + Binder.getCallingUid());
20290                    return;
20291                }
20292                mContext.enforceCallingOrSelfPermission(
20293                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20294            }
20295
20296            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20297            if (pir != null) {
20298                // Get all of the existing entries that exactly match this filter.
20299                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
20300                if (existing != null && existing.size() == 1) {
20301                    PreferredActivity cur = existing.get(0);
20302                    if (DEBUG_PREFERRED) {
20303                        Slog.i(TAG, "Checking replace of preferred:");
20304                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20305                        if (!cur.mPref.mAlways) {
20306                            Slog.i(TAG, "  -- CUR; not mAlways!");
20307                        } else {
20308                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
20309                            Slog.i(TAG, "  -- CUR: mSet="
20310                                    + Arrays.toString(cur.mPref.mSetComponents));
20311                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
20312                            Slog.i(TAG, "  -- NEW: mMatch="
20313                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
20314                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
20315                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
20316                        }
20317                    }
20318                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
20319                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
20320                            && cur.mPref.sameSet(set)) {
20321                        // Setting the preferred activity to what it happens to be already
20322                        if (DEBUG_PREFERRED) {
20323                            Slog.i(TAG, "Replacing with same preferred activity "
20324                                    + cur.mPref.mShortComponent + " for user "
20325                                    + userId + ":");
20326                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20327                        }
20328                        return;
20329                    }
20330                }
20331
20332                if (existing != null) {
20333                    if (DEBUG_PREFERRED) {
20334                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
20335                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20336                    }
20337                    for (int i = 0; i < existing.size(); i++) {
20338                        PreferredActivity pa = existing.get(i);
20339                        if (DEBUG_PREFERRED) {
20340                            Slog.i(TAG, "Removing existing preferred activity "
20341                                    + pa.mPref.mComponent + ":");
20342                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
20343                        }
20344                        pir.removeFilter(pa);
20345                    }
20346                }
20347            }
20348            addPreferredActivityInternal(filter, match, set, activity, true, userId,
20349                    "Replacing preferred");
20350        }
20351    }
20352
20353    @Override
20354    public void clearPackagePreferredActivities(String packageName) {
20355        final int callingUid = Binder.getCallingUid();
20356        if (getInstantAppPackageName(callingUid) != null) {
20357            return;
20358        }
20359        // writer
20360        synchronized (mPackages) {
20361            PackageParser.Package pkg = mPackages.get(packageName);
20362            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
20363                if (mContext.checkCallingOrSelfPermission(
20364                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20365                        != PackageManager.PERMISSION_GRANTED) {
20366                    if (getUidTargetSdkVersionLockedLPr(callingUid)
20367                            < Build.VERSION_CODES.FROYO) {
20368                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
20369                                + callingUid);
20370                        return;
20371                    }
20372                    mContext.enforceCallingOrSelfPermission(
20373                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20374                }
20375            }
20376            final PackageSetting ps = mSettings.getPackageLPr(packageName);
20377            if (ps != null
20378                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20379                return;
20380            }
20381            int user = UserHandle.getCallingUserId();
20382            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
20383                scheduleWritePackageRestrictionsLocked(user);
20384            }
20385        }
20386    }
20387
20388    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20389    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
20390        ArrayList<PreferredActivity> removed = null;
20391        boolean changed = false;
20392        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20393            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
20394            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20395            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
20396                continue;
20397            }
20398            Iterator<PreferredActivity> it = pir.filterIterator();
20399            while (it.hasNext()) {
20400                PreferredActivity pa = it.next();
20401                // Mark entry for removal only if it matches the package name
20402                // and the entry is of type "always".
20403                if (packageName == null ||
20404                        (pa.mPref.mComponent.getPackageName().equals(packageName)
20405                                && pa.mPref.mAlways)) {
20406                    if (removed == null) {
20407                        removed = new ArrayList<PreferredActivity>();
20408                    }
20409                    removed.add(pa);
20410                }
20411            }
20412            if (removed != null) {
20413                for (int j=0; j<removed.size(); j++) {
20414                    PreferredActivity pa = removed.get(j);
20415                    pir.removeFilter(pa);
20416                }
20417                changed = true;
20418            }
20419        }
20420        if (changed) {
20421            postPreferredActivityChangedBroadcast(userId);
20422        }
20423        return changed;
20424    }
20425
20426    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20427    private void clearIntentFilterVerificationsLPw(int userId) {
20428        final int packageCount = mPackages.size();
20429        for (int i = 0; i < packageCount; i++) {
20430            PackageParser.Package pkg = mPackages.valueAt(i);
20431            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
20432        }
20433    }
20434
20435    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20436    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
20437        if (userId == UserHandle.USER_ALL) {
20438            if (mSettings.removeIntentFilterVerificationLPw(packageName,
20439                    sUserManager.getUserIds())) {
20440                for (int oneUserId : sUserManager.getUserIds()) {
20441                    scheduleWritePackageRestrictionsLocked(oneUserId);
20442                }
20443            }
20444        } else {
20445            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
20446                scheduleWritePackageRestrictionsLocked(userId);
20447            }
20448        }
20449    }
20450
20451    /** Clears state for all users, and touches intent filter verification policy */
20452    void clearDefaultBrowserIfNeeded(String packageName) {
20453        for (int oneUserId : sUserManager.getUserIds()) {
20454            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
20455        }
20456    }
20457
20458    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
20459        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
20460        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
20461            if (packageName.equals(defaultBrowserPackageName)) {
20462                setDefaultBrowserPackageName(null, userId);
20463            }
20464        }
20465    }
20466
20467    @Override
20468    public void resetApplicationPreferences(int userId) {
20469        mContext.enforceCallingOrSelfPermission(
20470                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20471        final long identity = Binder.clearCallingIdentity();
20472        // writer
20473        try {
20474            synchronized (mPackages) {
20475                clearPackagePreferredActivitiesLPw(null, userId);
20476                mSettings.applyDefaultPreferredAppsLPw(this, userId);
20477                // TODO: We have to reset the default SMS and Phone. This requires
20478                // significant refactoring to keep all default apps in the package
20479                // manager (cleaner but more work) or have the services provide
20480                // callbacks to the package manager to request a default app reset.
20481                applyFactoryDefaultBrowserLPw(userId);
20482                clearIntentFilterVerificationsLPw(userId);
20483                primeDomainVerificationsLPw(userId);
20484                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
20485                scheduleWritePackageRestrictionsLocked(userId);
20486            }
20487            resetNetworkPolicies(userId);
20488        } finally {
20489            Binder.restoreCallingIdentity(identity);
20490        }
20491    }
20492
20493    @Override
20494    public int getPreferredActivities(List<IntentFilter> outFilters,
20495            List<ComponentName> outActivities, String packageName) {
20496        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20497            return 0;
20498        }
20499        int num = 0;
20500        final int userId = UserHandle.getCallingUserId();
20501        // reader
20502        synchronized (mPackages) {
20503            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20504            if (pir != null) {
20505                final Iterator<PreferredActivity> it = pir.filterIterator();
20506                while (it.hasNext()) {
20507                    final PreferredActivity pa = it.next();
20508                    if (packageName == null
20509                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
20510                                    && pa.mPref.mAlways)) {
20511                        if (outFilters != null) {
20512                            outFilters.add(new IntentFilter(pa));
20513                        }
20514                        if (outActivities != null) {
20515                            outActivities.add(pa.mPref.mComponent);
20516                        }
20517                    }
20518                }
20519            }
20520        }
20521
20522        return num;
20523    }
20524
20525    @Override
20526    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
20527            int userId) {
20528        int callingUid = Binder.getCallingUid();
20529        if (callingUid != Process.SYSTEM_UID) {
20530            throw new SecurityException(
20531                    "addPersistentPreferredActivity can only be run by the system");
20532        }
20533        if (filter.countActions() == 0) {
20534            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20535            return;
20536        }
20537        synchronized (mPackages) {
20538            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
20539                    ":");
20540            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20541            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
20542                    new PersistentPreferredActivity(filter, activity));
20543            scheduleWritePackageRestrictionsLocked(userId);
20544            postPreferredActivityChangedBroadcast(userId);
20545        }
20546    }
20547
20548    @Override
20549    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
20550        int callingUid = Binder.getCallingUid();
20551        if (callingUid != Process.SYSTEM_UID) {
20552            throw new SecurityException(
20553                    "clearPackagePersistentPreferredActivities can only be run by the system");
20554        }
20555        ArrayList<PersistentPreferredActivity> removed = null;
20556        boolean changed = false;
20557        synchronized (mPackages) {
20558            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
20559                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
20560                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
20561                        .valueAt(i);
20562                if (userId != thisUserId) {
20563                    continue;
20564                }
20565                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
20566                while (it.hasNext()) {
20567                    PersistentPreferredActivity ppa = it.next();
20568                    // Mark entry for removal only if it matches the package name.
20569                    if (ppa.mComponent.getPackageName().equals(packageName)) {
20570                        if (removed == null) {
20571                            removed = new ArrayList<PersistentPreferredActivity>();
20572                        }
20573                        removed.add(ppa);
20574                    }
20575                }
20576                if (removed != null) {
20577                    for (int j=0; j<removed.size(); j++) {
20578                        PersistentPreferredActivity ppa = removed.get(j);
20579                        ppir.removeFilter(ppa);
20580                    }
20581                    changed = true;
20582                }
20583            }
20584
20585            if (changed) {
20586                scheduleWritePackageRestrictionsLocked(userId);
20587                postPreferredActivityChangedBroadcast(userId);
20588            }
20589        }
20590    }
20591
20592    /**
20593     * Common machinery for picking apart a restored XML blob and passing
20594     * it to a caller-supplied functor to be applied to the running system.
20595     */
20596    private void restoreFromXml(XmlPullParser parser, int userId,
20597            String expectedStartTag, BlobXmlRestorer functor)
20598            throws IOException, XmlPullParserException {
20599        int type;
20600        while ((type = parser.next()) != XmlPullParser.START_TAG
20601                && type != XmlPullParser.END_DOCUMENT) {
20602        }
20603        if (type != XmlPullParser.START_TAG) {
20604            // oops didn't find a start tag?!
20605            if (DEBUG_BACKUP) {
20606                Slog.e(TAG, "Didn't find start tag during restore");
20607            }
20608            return;
20609        }
20610Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
20611        // this is supposed to be TAG_PREFERRED_BACKUP
20612        if (!expectedStartTag.equals(parser.getName())) {
20613            if (DEBUG_BACKUP) {
20614                Slog.e(TAG, "Found unexpected tag " + parser.getName());
20615            }
20616            return;
20617        }
20618
20619        // skip interfering stuff, then we're aligned with the backing implementation
20620        while ((type = parser.next()) == XmlPullParser.TEXT) { }
20621Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
20622        functor.apply(parser, userId);
20623    }
20624
20625    private interface BlobXmlRestorer {
20626        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
20627    }
20628
20629    /**
20630     * Non-Binder method, support for the backup/restore mechanism: write the
20631     * full set of preferred activities in its canonical XML format.  Returns the
20632     * XML output as a byte array, or null if there is none.
20633     */
20634    @Override
20635    public byte[] getPreferredActivityBackup(int userId) {
20636        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20637            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
20638        }
20639
20640        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20641        try {
20642            final XmlSerializer serializer = new FastXmlSerializer();
20643            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20644            serializer.startDocument(null, true);
20645            serializer.startTag(null, TAG_PREFERRED_BACKUP);
20646
20647            synchronized (mPackages) {
20648                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
20649            }
20650
20651            serializer.endTag(null, TAG_PREFERRED_BACKUP);
20652            serializer.endDocument();
20653            serializer.flush();
20654        } catch (Exception e) {
20655            if (DEBUG_BACKUP) {
20656                Slog.e(TAG, "Unable to write preferred activities for backup", e);
20657            }
20658            return null;
20659        }
20660
20661        return dataStream.toByteArray();
20662    }
20663
20664    @Override
20665    public void restorePreferredActivities(byte[] backup, int userId) {
20666        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20667            throw new SecurityException("Only the system may call restorePreferredActivities()");
20668        }
20669
20670        try {
20671            final XmlPullParser parser = Xml.newPullParser();
20672            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20673            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
20674                    new BlobXmlRestorer() {
20675                        @Override
20676                        public void apply(XmlPullParser parser, int userId)
20677                                throws XmlPullParserException, IOException {
20678                            synchronized (mPackages) {
20679                                mSettings.readPreferredActivitiesLPw(parser, userId);
20680                            }
20681                        }
20682                    } );
20683        } catch (Exception e) {
20684            if (DEBUG_BACKUP) {
20685                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20686            }
20687        }
20688    }
20689
20690    /**
20691     * Non-Binder method, support for the backup/restore mechanism: write the
20692     * default browser (etc) settings in its canonical XML format.  Returns the default
20693     * browser XML representation as a byte array, or null if there is none.
20694     */
20695    @Override
20696    public byte[] getDefaultAppsBackup(int userId) {
20697        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20698            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
20699        }
20700
20701        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20702        try {
20703            final XmlSerializer serializer = new FastXmlSerializer();
20704            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20705            serializer.startDocument(null, true);
20706            serializer.startTag(null, TAG_DEFAULT_APPS);
20707
20708            synchronized (mPackages) {
20709                mSettings.writeDefaultAppsLPr(serializer, userId);
20710            }
20711
20712            serializer.endTag(null, TAG_DEFAULT_APPS);
20713            serializer.endDocument();
20714            serializer.flush();
20715        } catch (Exception e) {
20716            if (DEBUG_BACKUP) {
20717                Slog.e(TAG, "Unable to write default apps for backup", e);
20718            }
20719            return null;
20720        }
20721
20722        return dataStream.toByteArray();
20723    }
20724
20725    @Override
20726    public void restoreDefaultApps(byte[] backup, int userId) {
20727        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20728            throw new SecurityException("Only the system may call restoreDefaultApps()");
20729        }
20730
20731        try {
20732            final XmlPullParser parser = Xml.newPullParser();
20733            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20734            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
20735                    new BlobXmlRestorer() {
20736                        @Override
20737                        public void apply(XmlPullParser parser, int userId)
20738                                throws XmlPullParserException, IOException {
20739                            synchronized (mPackages) {
20740                                mSettings.readDefaultAppsLPw(parser, userId);
20741                            }
20742                        }
20743                    } );
20744        } catch (Exception e) {
20745            if (DEBUG_BACKUP) {
20746                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
20747            }
20748        }
20749    }
20750
20751    @Override
20752    public byte[] getIntentFilterVerificationBackup(int userId) {
20753        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20754            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
20755        }
20756
20757        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20758        try {
20759            final XmlSerializer serializer = new FastXmlSerializer();
20760            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20761            serializer.startDocument(null, true);
20762            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
20763
20764            synchronized (mPackages) {
20765                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
20766            }
20767
20768            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
20769            serializer.endDocument();
20770            serializer.flush();
20771        } catch (Exception e) {
20772            if (DEBUG_BACKUP) {
20773                Slog.e(TAG, "Unable to write default apps for backup", e);
20774            }
20775            return null;
20776        }
20777
20778        return dataStream.toByteArray();
20779    }
20780
20781    @Override
20782    public void restoreIntentFilterVerification(byte[] backup, int userId) {
20783        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20784            throw new SecurityException("Only the system may call restorePreferredActivities()");
20785        }
20786
20787        try {
20788            final XmlPullParser parser = Xml.newPullParser();
20789            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20790            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
20791                    new BlobXmlRestorer() {
20792                        @Override
20793                        public void apply(XmlPullParser parser, int userId)
20794                                throws XmlPullParserException, IOException {
20795                            synchronized (mPackages) {
20796                                mSettings.readAllDomainVerificationsLPr(parser, userId);
20797                                mSettings.writeLPr();
20798                            }
20799                        }
20800                    } );
20801        } catch (Exception e) {
20802            if (DEBUG_BACKUP) {
20803                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20804            }
20805        }
20806    }
20807
20808    @Override
20809    public byte[] getPermissionGrantBackup(int userId) {
20810        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20811            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
20812        }
20813
20814        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20815        try {
20816            final XmlSerializer serializer = new FastXmlSerializer();
20817            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20818            serializer.startDocument(null, true);
20819            serializer.startTag(null, TAG_PERMISSION_BACKUP);
20820
20821            synchronized (mPackages) {
20822                serializeRuntimePermissionGrantsLPr(serializer, userId);
20823            }
20824
20825            serializer.endTag(null, TAG_PERMISSION_BACKUP);
20826            serializer.endDocument();
20827            serializer.flush();
20828        } catch (Exception e) {
20829            if (DEBUG_BACKUP) {
20830                Slog.e(TAG, "Unable to write default apps for backup", e);
20831            }
20832            return null;
20833        }
20834
20835        return dataStream.toByteArray();
20836    }
20837
20838    @Override
20839    public void restorePermissionGrants(byte[] backup, int userId) {
20840        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20841            throw new SecurityException("Only the system may call restorePermissionGrants()");
20842        }
20843
20844        try {
20845            final XmlPullParser parser = Xml.newPullParser();
20846            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20847            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
20848                    new BlobXmlRestorer() {
20849                        @Override
20850                        public void apply(XmlPullParser parser, int userId)
20851                                throws XmlPullParserException, IOException {
20852                            synchronized (mPackages) {
20853                                processRestoredPermissionGrantsLPr(parser, userId);
20854                            }
20855                        }
20856                    } );
20857        } catch (Exception e) {
20858            if (DEBUG_BACKUP) {
20859                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20860            }
20861        }
20862    }
20863
20864    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
20865            throws IOException {
20866        serializer.startTag(null, TAG_ALL_GRANTS);
20867
20868        final int N = mSettings.mPackages.size();
20869        for (int i = 0; i < N; i++) {
20870            final PackageSetting ps = mSettings.mPackages.valueAt(i);
20871            boolean pkgGrantsKnown = false;
20872
20873            PermissionsState packagePerms = ps.getPermissionsState();
20874
20875            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
20876                final int grantFlags = state.getFlags();
20877                // only look at grants that are not system/policy fixed
20878                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
20879                    final boolean isGranted = state.isGranted();
20880                    // And only back up the user-twiddled state bits
20881                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
20882                        final String packageName = mSettings.mPackages.keyAt(i);
20883                        if (!pkgGrantsKnown) {
20884                            serializer.startTag(null, TAG_GRANT);
20885                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
20886                            pkgGrantsKnown = true;
20887                        }
20888
20889                        final boolean userSet =
20890                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
20891                        final boolean userFixed =
20892                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
20893                        final boolean revoke =
20894                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
20895
20896                        serializer.startTag(null, TAG_PERMISSION);
20897                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
20898                        if (isGranted) {
20899                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
20900                        }
20901                        if (userSet) {
20902                            serializer.attribute(null, ATTR_USER_SET, "true");
20903                        }
20904                        if (userFixed) {
20905                            serializer.attribute(null, ATTR_USER_FIXED, "true");
20906                        }
20907                        if (revoke) {
20908                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
20909                        }
20910                        serializer.endTag(null, TAG_PERMISSION);
20911                    }
20912                }
20913            }
20914
20915            if (pkgGrantsKnown) {
20916                serializer.endTag(null, TAG_GRANT);
20917            }
20918        }
20919
20920        serializer.endTag(null, TAG_ALL_GRANTS);
20921    }
20922
20923    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
20924            throws XmlPullParserException, IOException {
20925        String pkgName = null;
20926        int outerDepth = parser.getDepth();
20927        int type;
20928        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
20929                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
20930            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
20931                continue;
20932            }
20933
20934            final String tagName = parser.getName();
20935            if (tagName.equals(TAG_GRANT)) {
20936                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
20937                if (DEBUG_BACKUP) {
20938                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
20939                }
20940            } else if (tagName.equals(TAG_PERMISSION)) {
20941
20942                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
20943                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
20944
20945                int newFlagSet = 0;
20946                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
20947                    newFlagSet |= FLAG_PERMISSION_USER_SET;
20948                }
20949                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
20950                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
20951                }
20952                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
20953                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
20954                }
20955                if (DEBUG_BACKUP) {
20956                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
20957                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
20958                }
20959                final PackageSetting ps = mSettings.mPackages.get(pkgName);
20960                if (ps != null) {
20961                    // Already installed so we apply the grant immediately
20962                    if (DEBUG_BACKUP) {
20963                        Slog.v(TAG, "        + already installed; applying");
20964                    }
20965                    PermissionsState perms = ps.getPermissionsState();
20966                    BasePermission bp = mSettings.mPermissions.get(permName);
20967                    if (bp != null) {
20968                        if (isGranted) {
20969                            perms.grantRuntimePermission(bp, userId);
20970                        }
20971                        if (newFlagSet != 0) {
20972                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
20973                        }
20974                    }
20975                } else {
20976                    // Need to wait for post-restore install to apply the grant
20977                    if (DEBUG_BACKUP) {
20978                        Slog.v(TAG, "        - not yet installed; saving for later");
20979                    }
20980                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
20981                            isGranted, newFlagSet, userId);
20982                }
20983            } else {
20984                PackageManagerService.reportSettingsProblem(Log.WARN,
20985                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
20986                XmlUtils.skipCurrentTag(parser);
20987            }
20988        }
20989
20990        scheduleWriteSettingsLocked();
20991        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
20992    }
20993
20994    @Override
20995    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
20996            int sourceUserId, int targetUserId, int flags) {
20997        mContext.enforceCallingOrSelfPermission(
20998                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20999        int callingUid = Binder.getCallingUid();
21000        enforceOwnerRights(ownerPackage, callingUid);
21001        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
21002        if (intentFilter.countActions() == 0) {
21003            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
21004            return;
21005        }
21006        synchronized (mPackages) {
21007            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
21008                    ownerPackage, targetUserId, flags);
21009            CrossProfileIntentResolver resolver =
21010                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
21011            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
21012            // We have all those whose filter is equal. Now checking if the rest is equal as well.
21013            if (existing != null) {
21014                int size = existing.size();
21015                for (int i = 0; i < size; i++) {
21016                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
21017                        return;
21018                    }
21019                }
21020            }
21021            resolver.addFilter(newFilter);
21022            scheduleWritePackageRestrictionsLocked(sourceUserId);
21023        }
21024    }
21025
21026    @Override
21027    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
21028        mContext.enforceCallingOrSelfPermission(
21029                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
21030        final int callingUid = Binder.getCallingUid();
21031        enforceOwnerRights(ownerPackage, callingUid);
21032        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
21033        synchronized (mPackages) {
21034            CrossProfileIntentResolver resolver =
21035                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
21036            ArraySet<CrossProfileIntentFilter> set =
21037                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
21038            for (CrossProfileIntentFilter filter : set) {
21039                if (filter.getOwnerPackage().equals(ownerPackage)) {
21040                    resolver.removeFilter(filter);
21041                }
21042            }
21043            scheduleWritePackageRestrictionsLocked(sourceUserId);
21044        }
21045    }
21046
21047    // Enforcing that callingUid is owning pkg on userId
21048    private void enforceOwnerRights(String pkg, int callingUid) {
21049        // The system owns everything.
21050        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
21051            return;
21052        }
21053        final int callingUserId = UserHandle.getUserId(callingUid);
21054        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
21055        if (pi == null) {
21056            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
21057                    + callingUserId);
21058        }
21059        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
21060            throw new SecurityException("Calling uid " + callingUid
21061                    + " does not own package " + pkg);
21062        }
21063    }
21064
21065    @Override
21066    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
21067        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21068            return null;
21069        }
21070        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
21071    }
21072
21073    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
21074        UserManagerService ums = UserManagerService.getInstance();
21075        if (ums != null) {
21076            final UserInfo parent = ums.getProfileParent(userId);
21077            final int launcherUid = (parent != null) ? parent.id : userId;
21078            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
21079            if (launcherComponent != null) {
21080                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
21081                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
21082                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
21083                        .setPackage(launcherComponent.getPackageName());
21084                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
21085            }
21086        }
21087    }
21088
21089    /**
21090     * Report the 'Home' activity which is currently set as "always use this one". If non is set
21091     * then reports the most likely home activity or null if there are more than one.
21092     */
21093    private ComponentName getDefaultHomeActivity(int userId) {
21094        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
21095        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
21096        if (cn != null) {
21097            return cn;
21098        }
21099
21100        // Find the launcher with the highest priority and return that component if there are no
21101        // other home activity with the same priority.
21102        int lastPriority = Integer.MIN_VALUE;
21103        ComponentName lastComponent = null;
21104        final int size = allHomeCandidates.size();
21105        for (int i = 0; i < size; i++) {
21106            final ResolveInfo ri = allHomeCandidates.get(i);
21107            if (ri.priority > lastPriority) {
21108                lastComponent = ri.activityInfo.getComponentName();
21109                lastPriority = ri.priority;
21110            } else if (ri.priority == lastPriority) {
21111                // Two components found with same priority.
21112                lastComponent = null;
21113            }
21114        }
21115        return lastComponent;
21116    }
21117
21118    private Intent getHomeIntent() {
21119        Intent intent = new Intent(Intent.ACTION_MAIN);
21120        intent.addCategory(Intent.CATEGORY_HOME);
21121        intent.addCategory(Intent.CATEGORY_DEFAULT);
21122        return intent;
21123    }
21124
21125    private IntentFilter getHomeFilter() {
21126        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
21127        filter.addCategory(Intent.CATEGORY_HOME);
21128        filter.addCategory(Intent.CATEGORY_DEFAULT);
21129        return filter;
21130    }
21131
21132    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
21133            int userId) {
21134        Intent intent  = getHomeIntent();
21135        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
21136                PackageManager.GET_META_DATA, userId);
21137        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
21138                true, false, false, userId);
21139
21140        allHomeCandidates.clear();
21141        if (list != null) {
21142            for (ResolveInfo ri : list) {
21143                allHomeCandidates.add(ri);
21144            }
21145        }
21146        return (preferred == null || preferred.activityInfo == null)
21147                ? null
21148                : new ComponentName(preferred.activityInfo.packageName,
21149                        preferred.activityInfo.name);
21150    }
21151
21152    @Override
21153    public void setHomeActivity(ComponentName comp, int userId) {
21154        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21155            return;
21156        }
21157        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
21158        getHomeActivitiesAsUser(homeActivities, userId);
21159
21160        boolean found = false;
21161
21162        final int size = homeActivities.size();
21163        final ComponentName[] set = new ComponentName[size];
21164        for (int i = 0; i < size; i++) {
21165            final ResolveInfo candidate = homeActivities.get(i);
21166            final ActivityInfo info = candidate.activityInfo;
21167            final ComponentName activityName = new ComponentName(info.packageName, info.name);
21168            set[i] = activityName;
21169            if (!found && activityName.equals(comp)) {
21170                found = true;
21171            }
21172        }
21173        if (!found) {
21174            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
21175                    + userId);
21176        }
21177        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
21178                set, comp, userId);
21179    }
21180
21181    private @Nullable String getSetupWizardPackageName() {
21182        final Intent intent = new Intent(Intent.ACTION_MAIN);
21183        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
21184
21185        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21186                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21187                        | MATCH_DISABLED_COMPONENTS,
21188                UserHandle.myUserId());
21189        if (matches.size() == 1) {
21190            return matches.get(0).getComponentInfo().packageName;
21191        } else {
21192            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
21193                    + ": matches=" + matches);
21194            return null;
21195        }
21196    }
21197
21198    private @Nullable String getStorageManagerPackageName() {
21199        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
21200
21201        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21202                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21203                        | MATCH_DISABLED_COMPONENTS,
21204                UserHandle.myUserId());
21205        if (matches.size() == 1) {
21206            return matches.get(0).getComponentInfo().packageName;
21207        } else {
21208            Slog.e(TAG, "There should probably be exactly one storage manager; found "
21209                    + matches.size() + ": matches=" + matches);
21210            return null;
21211        }
21212    }
21213
21214    @Override
21215    public void setApplicationEnabledSetting(String appPackageName,
21216            int newState, int flags, int userId, String callingPackage) {
21217        if (!sUserManager.exists(userId)) return;
21218        if (callingPackage == null) {
21219            callingPackage = Integer.toString(Binder.getCallingUid());
21220        }
21221        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
21222    }
21223
21224    @Override
21225    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
21226        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
21227        synchronized (mPackages) {
21228            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
21229            if (pkgSetting != null) {
21230                pkgSetting.setUpdateAvailable(updateAvailable);
21231            }
21232        }
21233    }
21234
21235    @Override
21236    public void setComponentEnabledSetting(ComponentName componentName,
21237            int newState, int flags, int userId) {
21238        if (!sUserManager.exists(userId)) return;
21239        setEnabledSetting(componentName.getPackageName(),
21240                componentName.getClassName(), newState, flags, userId, null);
21241    }
21242
21243    private void setEnabledSetting(final String packageName, String className, int newState,
21244            final int flags, int userId, String callingPackage) {
21245        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
21246              || newState == COMPONENT_ENABLED_STATE_ENABLED
21247              || newState == COMPONENT_ENABLED_STATE_DISABLED
21248              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21249              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
21250            throw new IllegalArgumentException("Invalid new component state: "
21251                    + newState);
21252        }
21253        PackageSetting pkgSetting;
21254        final int callingUid = Binder.getCallingUid();
21255        final int permission;
21256        if (callingUid == Process.SYSTEM_UID) {
21257            permission = PackageManager.PERMISSION_GRANTED;
21258        } else {
21259            permission = mContext.checkCallingOrSelfPermission(
21260                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21261        }
21262        enforceCrossUserPermission(callingUid, userId,
21263                false /* requireFullPermission */, true /* checkShell */, "set enabled");
21264        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21265        boolean sendNow = false;
21266        boolean isApp = (className == null);
21267        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
21268        String componentName = isApp ? packageName : className;
21269        int packageUid = -1;
21270        ArrayList<String> components;
21271
21272        // reader
21273        synchronized (mPackages) {
21274            pkgSetting = mSettings.mPackages.get(packageName);
21275            if (pkgSetting == null) {
21276                if (!isCallerInstantApp) {
21277                    if (className == null) {
21278                        throw new IllegalArgumentException("Unknown package: " + packageName);
21279                    }
21280                    throw new IllegalArgumentException(
21281                            "Unknown component: " + packageName + "/" + className);
21282                } else {
21283                    // throw SecurityException to prevent leaking package information
21284                    throw new SecurityException(
21285                            "Attempt to change component state; "
21286                            + "pid=" + Binder.getCallingPid()
21287                            + ", uid=" + callingUid
21288                            + (className == null
21289                                    ? ", package=" + packageName
21290                                    : ", component=" + packageName + "/" + className));
21291                }
21292            }
21293        }
21294
21295        // Limit who can change which apps
21296        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
21297            // Don't allow apps that don't have permission to modify other apps
21298            if (!allowedByPermission
21299                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
21300                throw new SecurityException(
21301                        "Attempt to change component state; "
21302                        + "pid=" + Binder.getCallingPid()
21303                        + ", uid=" + callingUid
21304                        + (className == null
21305                                ? ", package=" + packageName
21306                                : ", component=" + packageName + "/" + className));
21307            }
21308            // Don't allow changing protected packages.
21309            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
21310                throw new SecurityException("Cannot disable a protected package: " + packageName);
21311            }
21312        }
21313
21314        synchronized (mPackages) {
21315            if (callingUid == Process.SHELL_UID
21316                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
21317                // Shell can only change whole packages between ENABLED and DISABLED_USER states
21318                // unless it is a test package.
21319                int oldState = pkgSetting.getEnabled(userId);
21320                if (className == null
21321                    &&
21322                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
21323                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
21324                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
21325                    &&
21326                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21327                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
21328                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
21329                    // ok
21330                } else {
21331                    throw new SecurityException(
21332                            "Shell cannot change component state for " + packageName + "/"
21333                            + className + " to " + newState);
21334                }
21335            }
21336            if (className == null) {
21337                // We're dealing with an application/package level state change
21338                if (pkgSetting.getEnabled(userId) == newState) {
21339                    // Nothing to do
21340                    return;
21341                }
21342                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
21343                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
21344                    // Don't care about who enables an app.
21345                    callingPackage = null;
21346                }
21347                pkgSetting.setEnabled(newState, userId, callingPackage);
21348                // pkgSetting.pkg.mSetEnabled = newState;
21349            } else {
21350                // We're dealing with a component level state change
21351                // First, verify that this is a valid class name.
21352                PackageParser.Package pkg = pkgSetting.pkg;
21353                if (pkg == null || !pkg.hasComponentClassName(className)) {
21354                    if (pkg != null &&
21355                            pkg.applicationInfo.targetSdkVersion >=
21356                                    Build.VERSION_CODES.JELLY_BEAN) {
21357                        throw new IllegalArgumentException("Component class " + className
21358                                + " does not exist in " + packageName);
21359                    } else {
21360                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
21361                                + className + " does not exist in " + packageName);
21362                    }
21363                }
21364                switch (newState) {
21365                case COMPONENT_ENABLED_STATE_ENABLED:
21366                    if (!pkgSetting.enableComponentLPw(className, userId)) {
21367                        return;
21368                    }
21369                    break;
21370                case COMPONENT_ENABLED_STATE_DISABLED:
21371                    if (!pkgSetting.disableComponentLPw(className, userId)) {
21372                        return;
21373                    }
21374                    break;
21375                case COMPONENT_ENABLED_STATE_DEFAULT:
21376                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
21377                        return;
21378                    }
21379                    break;
21380                default:
21381                    Slog.e(TAG, "Invalid new component state: " + newState);
21382                    return;
21383                }
21384            }
21385            scheduleWritePackageRestrictionsLocked(userId);
21386            updateSequenceNumberLP(pkgSetting, new int[] { userId });
21387            final long callingId = Binder.clearCallingIdentity();
21388            try {
21389                updateInstantAppInstallerLocked(packageName);
21390            } finally {
21391                Binder.restoreCallingIdentity(callingId);
21392            }
21393            components = mPendingBroadcasts.get(userId, packageName);
21394            final boolean newPackage = components == null;
21395            if (newPackage) {
21396                components = new ArrayList<String>();
21397            }
21398            if (!components.contains(componentName)) {
21399                components.add(componentName);
21400            }
21401            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
21402                sendNow = true;
21403                // Purge entry from pending broadcast list if another one exists already
21404                // since we are sending one right away.
21405                mPendingBroadcasts.remove(userId, packageName);
21406            } else {
21407                if (newPackage) {
21408                    mPendingBroadcasts.put(userId, packageName, components);
21409                }
21410                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
21411                    // Schedule a message
21412                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
21413                }
21414            }
21415        }
21416
21417        long callingId = Binder.clearCallingIdentity();
21418        try {
21419            if (sendNow) {
21420                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
21421                sendPackageChangedBroadcast(packageName,
21422                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
21423            }
21424        } finally {
21425            Binder.restoreCallingIdentity(callingId);
21426        }
21427    }
21428
21429    @Override
21430    public void flushPackageRestrictionsAsUser(int userId) {
21431        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21432            return;
21433        }
21434        if (!sUserManager.exists(userId)) {
21435            return;
21436        }
21437        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
21438                false /* checkShell */, "flushPackageRestrictions");
21439        synchronized (mPackages) {
21440            mSettings.writePackageRestrictionsLPr(userId);
21441            mDirtyUsers.remove(userId);
21442            if (mDirtyUsers.isEmpty()) {
21443                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
21444            }
21445        }
21446    }
21447
21448    private void sendPackageChangedBroadcast(String packageName,
21449            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
21450        if (DEBUG_INSTALL)
21451            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
21452                    + componentNames);
21453        Bundle extras = new Bundle(4);
21454        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
21455        String nameList[] = new String[componentNames.size()];
21456        componentNames.toArray(nameList);
21457        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
21458        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
21459        extras.putInt(Intent.EXTRA_UID, packageUid);
21460        // If this is not reporting a change of the overall package, then only send it
21461        // to registered receivers.  We don't want to launch a swath of apps for every
21462        // little component state change.
21463        final int flags = !componentNames.contains(packageName)
21464                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
21465        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
21466                new int[] {UserHandle.getUserId(packageUid)});
21467    }
21468
21469    @Override
21470    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
21471        if (!sUserManager.exists(userId)) return;
21472        final int callingUid = Binder.getCallingUid();
21473        if (getInstantAppPackageName(callingUid) != null) {
21474            return;
21475        }
21476        final int permission = mContext.checkCallingOrSelfPermission(
21477                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21478        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21479        enforceCrossUserPermission(callingUid, userId,
21480                true /* requireFullPermission */, true /* checkShell */, "stop package");
21481        // writer
21482        synchronized (mPackages) {
21483            final PackageSetting ps = mSettings.mPackages.get(packageName);
21484            if (!filterAppAccessLPr(ps, callingUid, userId)
21485                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
21486                            allowedByPermission, callingUid, userId)) {
21487                scheduleWritePackageRestrictionsLocked(userId);
21488            }
21489        }
21490    }
21491
21492    @Override
21493    public String getInstallerPackageName(String packageName) {
21494        final int callingUid = Binder.getCallingUid();
21495        if (getInstantAppPackageName(callingUid) != null) {
21496            return null;
21497        }
21498        // reader
21499        synchronized (mPackages) {
21500            final PackageSetting ps = mSettings.mPackages.get(packageName);
21501            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
21502                return null;
21503            }
21504            return mSettings.getInstallerPackageNameLPr(packageName);
21505        }
21506    }
21507
21508    public boolean isOrphaned(String packageName) {
21509        // reader
21510        synchronized (mPackages) {
21511            return mSettings.isOrphaned(packageName);
21512        }
21513    }
21514
21515    @Override
21516    public int getApplicationEnabledSetting(String packageName, int userId) {
21517        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
21518        int callingUid = Binder.getCallingUid();
21519        enforceCrossUserPermission(callingUid, userId,
21520                false /* requireFullPermission */, false /* checkShell */, "get enabled");
21521        // reader
21522        synchronized (mPackages) {
21523            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
21524                return COMPONENT_ENABLED_STATE_DISABLED;
21525            }
21526            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
21527        }
21528    }
21529
21530    @Override
21531    public int getComponentEnabledSetting(ComponentName component, int userId) {
21532        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
21533        int callingUid = Binder.getCallingUid();
21534        enforceCrossUserPermission(callingUid, userId,
21535                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
21536        synchronized (mPackages) {
21537            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
21538                    component, TYPE_UNKNOWN, userId)) {
21539                return COMPONENT_ENABLED_STATE_DISABLED;
21540            }
21541            return mSettings.getComponentEnabledSettingLPr(component, userId);
21542        }
21543    }
21544
21545    @Override
21546    public void enterSafeMode() {
21547        enforceSystemOrRoot("Only the system can request entering safe mode");
21548
21549        if (!mSystemReady) {
21550            mSafeMode = true;
21551        }
21552    }
21553
21554    @Override
21555    public void systemReady() {
21556        enforceSystemOrRoot("Only the system can claim the system is ready");
21557
21558        mSystemReady = true;
21559        final ContentResolver resolver = mContext.getContentResolver();
21560        ContentObserver co = new ContentObserver(mHandler) {
21561            @Override
21562            public void onChange(boolean selfChange) {
21563                mEphemeralAppsDisabled =
21564                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
21565                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
21566            }
21567        };
21568        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
21569                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
21570                false, co, UserHandle.USER_SYSTEM);
21571        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
21572                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
21573        co.onChange(true);
21574
21575        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
21576        // disabled after already being started.
21577        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
21578                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
21579
21580        // Read the compatibilty setting when the system is ready.
21581        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
21582                mContext.getContentResolver(),
21583                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
21584        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
21585        if (DEBUG_SETTINGS) {
21586            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
21587        }
21588
21589        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
21590
21591        synchronized (mPackages) {
21592            // Verify that all of the preferred activity components actually
21593            // exist.  It is possible for applications to be updated and at
21594            // that point remove a previously declared activity component that
21595            // had been set as a preferred activity.  We try to clean this up
21596            // the next time we encounter that preferred activity, but it is
21597            // possible for the user flow to never be able to return to that
21598            // situation so here we do a sanity check to make sure we haven't
21599            // left any junk around.
21600            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
21601            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21602                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21603                removed.clear();
21604                for (PreferredActivity pa : pir.filterSet()) {
21605                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
21606                        removed.add(pa);
21607                    }
21608                }
21609                if (removed.size() > 0) {
21610                    for (int r=0; r<removed.size(); r++) {
21611                        PreferredActivity pa = removed.get(r);
21612                        Slog.w(TAG, "Removing dangling preferred activity: "
21613                                + pa.mPref.mComponent);
21614                        pir.removeFilter(pa);
21615                    }
21616                    mSettings.writePackageRestrictionsLPr(
21617                            mSettings.mPreferredActivities.keyAt(i));
21618                }
21619            }
21620
21621            for (int userId : UserManagerService.getInstance().getUserIds()) {
21622                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
21623                    grantPermissionsUserIds = ArrayUtils.appendInt(
21624                            grantPermissionsUserIds, userId);
21625                }
21626            }
21627        }
21628        sUserManager.systemReady();
21629
21630        // If we upgraded grant all default permissions before kicking off.
21631        for (int userId : grantPermissionsUserIds) {
21632            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
21633        }
21634
21635        // If we did not grant default permissions, we preload from this the
21636        // default permission exceptions lazily to ensure we don't hit the
21637        // disk on a new user creation.
21638        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
21639            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
21640        }
21641
21642        // Kick off any messages waiting for system ready
21643        if (mPostSystemReadyMessages != null) {
21644            for (Message msg : mPostSystemReadyMessages) {
21645                msg.sendToTarget();
21646            }
21647            mPostSystemReadyMessages = null;
21648        }
21649
21650        // Watch for external volumes that come and go over time
21651        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21652        storage.registerListener(mStorageListener);
21653
21654        mInstallerService.systemReady();
21655        mPackageDexOptimizer.systemReady();
21656
21657        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
21658                StorageManagerInternal.class);
21659        StorageManagerInternal.addExternalStoragePolicy(
21660                new StorageManagerInternal.ExternalStorageMountPolicy() {
21661            @Override
21662            public int getMountMode(int uid, String packageName) {
21663                if (Process.isIsolated(uid)) {
21664                    return Zygote.MOUNT_EXTERNAL_NONE;
21665                }
21666                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
21667                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21668                }
21669                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21670                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21671                }
21672                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21673                    return Zygote.MOUNT_EXTERNAL_READ;
21674                }
21675                return Zygote.MOUNT_EXTERNAL_WRITE;
21676            }
21677
21678            @Override
21679            public boolean hasExternalStorage(int uid, String packageName) {
21680                return true;
21681            }
21682        });
21683
21684        // Now that we're mostly running, clean up stale users and apps
21685        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
21686        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
21687
21688        if (mPrivappPermissionsViolations != null) {
21689            Slog.wtf(TAG,"Signature|privileged permissions not in "
21690                    + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
21691            mPrivappPermissionsViolations = null;
21692        }
21693    }
21694
21695    public void waitForAppDataPrepared() {
21696        if (mPrepareAppDataFuture == null) {
21697            return;
21698        }
21699        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
21700        mPrepareAppDataFuture = null;
21701    }
21702
21703    @Override
21704    public boolean isSafeMode() {
21705        // allow instant applications
21706        return mSafeMode;
21707    }
21708
21709    @Override
21710    public boolean hasSystemUidErrors() {
21711        // allow instant applications
21712        return mHasSystemUidErrors;
21713    }
21714
21715    static String arrayToString(int[] array) {
21716        StringBuffer buf = new StringBuffer(128);
21717        buf.append('[');
21718        if (array != null) {
21719            for (int i=0; i<array.length; i++) {
21720                if (i > 0) buf.append(", ");
21721                buf.append(array[i]);
21722            }
21723        }
21724        buf.append(']');
21725        return buf.toString();
21726    }
21727
21728    static class DumpState {
21729        public static final int DUMP_LIBS = 1 << 0;
21730        public static final int DUMP_FEATURES = 1 << 1;
21731        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
21732        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
21733        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
21734        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
21735        public static final int DUMP_PERMISSIONS = 1 << 6;
21736        public static final int DUMP_PACKAGES = 1 << 7;
21737        public static final int DUMP_SHARED_USERS = 1 << 8;
21738        public static final int DUMP_MESSAGES = 1 << 9;
21739        public static final int DUMP_PROVIDERS = 1 << 10;
21740        public static final int DUMP_VERIFIERS = 1 << 11;
21741        public static final int DUMP_PREFERRED = 1 << 12;
21742        public static final int DUMP_PREFERRED_XML = 1 << 13;
21743        public static final int DUMP_KEYSETS = 1 << 14;
21744        public static final int DUMP_VERSION = 1 << 15;
21745        public static final int DUMP_INSTALLS = 1 << 16;
21746        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
21747        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
21748        public static final int DUMP_FROZEN = 1 << 19;
21749        public static final int DUMP_DEXOPT = 1 << 20;
21750        public static final int DUMP_COMPILER_STATS = 1 << 21;
21751        public static final int DUMP_CHANGES = 1 << 22;
21752        public static final int DUMP_VOLUMES = 1 << 23;
21753
21754        public static final int OPTION_SHOW_FILTERS = 1 << 0;
21755
21756        private int mTypes;
21757
21758        private int mOptions;
21759
21760        private boolean mTitlePrinted;
21761
21762        private SharedUserSetting mSharedUser;
21763
21764        public boolean isDumping(int type) {
21765            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
21766                return true;
21767            }
21768
21769            return (mTypes & type) != 0;
21770        }
21771
21772        public void setDump(int type) {
21773            mTypes |= type;
21774        }
21775
21776        public boolean isOptionEnabled(int option) {
21777            return (mOptions & option) != 0;
21778        }
21779
21780        public void setOptionEnabled(int option) {
21781            mOptions |= option;
21782        }
21783
21784        public boolean onTitlePrinted() {
21785            final boolean printed = mTitlePrinted;
21786            mTitlePrinted = true;
21787            return printed;
21788        }
21789
21790        public boolean getTitlePrinted() {
21791            return mTitlePrinted;
21792        }
21793
21794        public void setTitlePrinted(boolean enabled) {
21795            mTitlePrinted = enabled;
21796        }
21797
21798        public SharedUserSetting getSharedUser() {
21799            return mSharedUser;
21800        }
21801
21802        public void setSharedUser(SharedUserSetting user) {
21803            mSharedUser = user;
21804        }
21805    }
21806
21807    @Override
21808    public void onShellCommand(FileDescriptor in, FileDescriptor out,
21809            FileDescriptor err, String[] args, ShellCallback callback,
21810            ResultReceiver resultReceiver) {
21811        (new PackageManagerShellCommand(this)).exec(
21812                this, in, out, err, args, callback, resultReceiver);
21813    }
21814
21815    @Override
21816    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
21817        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
21818
21819        DumpState dumpState = new DumpState();
21820        boolean fullPreferred = false;
21821        boolean checkin = false;
21822
21823        String packageName = null;
21824        ArraySet<String> permissionNames = null;
21825
21826        int opti = 0;
21827        while (opti < args.length) {
21828            String opt = args[opti];
21829            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
21830                break;
21831            }
21832            opti++;
21833
21834            if ("-a".equals(opt)) {
21835                // Right now we only know how to print all.
21836            } else if ("-h".equals(opt)) {
21837                pw.println("Package manager dump options:");
21838                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
21839                pw.println("    --checkin: dump for a checkin");
21840                pw.println("    -f: print details of intent filters");
21841                pw.println("    -h: print this help");
21842                pw.println("  cmd may be one of:");
21843                pw.println("    l[ibraries]: list known shared libraries");
21844                pw.println("    f[eatures]: list device features");
21845                pw.println("    k[eysets]: print known keysets");
21846                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
21847                pw.println("    perm[issions]: dump permissions");
21848                pw.println("    permission [name ...]: dump declaration and use of given permission");
21849                pw.println("    pref[erred]: print preferred package settings");
21850                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
21851                pw.println("    prov[iders]: dump content providers");
21852                pw.println("    p[ackages]: dump installed packages");
21853                pw.println("    s[hared-users]: dump shared user IDs");
21854                pw.println("    m[essages]: print collected runtime messages");
21855                pw.println("    v[erifiers]: print package verifier info");
21856                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
21857                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
21858                pw.println("    version: print database version info");
21859                pw.println("    write: write current settings now");
21860                pw.println("    installs: details about install sessions");
21861                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
21862                pw.println("    dexopt: dump dexopt state");
21863                pw.println("    compiler-stats: dump compiler statistics");
21864                pw.println("    enabled-overlays: dump list of enabled overlay packages");
21865                pw.println("    <package.name>: info about given package");
21866                return;
21867            } else if ("--checkin".equals(opt)) {
21868                checkin = true;
21869            } else if ("-f".equals(opt)) {
21870                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21871            } else if ("--proto".equals(opt)) {
21872                dumpProto(fd);
21873                return;
21874            } else {
21875                pw.println("Unknown argument: " + opt + "; use -h for help");
21876            }
21877        }
21878
21879        // Is the caller requesting to dump a particular piece of data?
21880        if (opti < args.length) {
21881            String cmd = args[opti];
21882            opti++;
21883            // Is this a package name?
21884            if ("android".equals(cmd) || cmd.contains(".")) {
21885                packageName = cmd;
21886                // When dumping a single package, we always dump all of its
21887                // filter information since the amount of data will be reasonable.
21888                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21889            } else if ("check-permission".equals(cmd)) {
21890                if (opti >= args.length) {
21891                    pw.println("Error: check-permission missing permission argument");
21892                    return;
21893                }
21894                String perm = args[opti];
21895                opti++;
21896                if (opti >= args.length) {
21897                    pw.println("Error: check-permission missing package argument");
21898                    return;
21899                }
21900
21901                String pkg = args[opti];
21902                opti++;
21903                int user = UserHandle.getUserId(Binder.getCallingUid());
21904                if (opti < args.length) {
21905                    try {
21906                        user = Integer.parseInt(args[opti]);
21907                    } catch (NumberFormatException e) {
21908                        pw.println("Error: check-permission user argument is not a number: "
21909                                + args[opti]);
21910                        return;
21911                    }
21912                }
21913
21914                // Normalize package name to handle renamed packages and static libs
21915                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
21916
21917                pw.println(checkPermission(perm, pkg, user));
21918                return;
21919            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
21920                dumpState.setDump(DumpState.DUMP_LIBS);
21921            } else if ("f".equals(cmd) || "features".equals(cmd)) {
21922                dumpState.setDump(DumpState.DUMP_FEATURES);
21923            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
21924                if (opti >= args.length) {
21925                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
21926                            | DumpState.DUMP_SERVICE_RESOLVERS
21927                            | DumpState.DUMP_RECEIVER_RESOLVERS
21928                            | DumpState.DUMP_CONTENT_RESOLVERS);
21929                } else {
21930                    while (opti < args.length) {
21931                        String name = args[opti];
21932                        if ("a".equals(name) || "activity".equals(name)) {
21933                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
21934                        } else if ("s".equals(name) || "service".equals(name)) {
21935                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
21936                        } else if ("r".equals(name) || "receiver".equals(name)) {
21937                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
21938                        } else if ("c".equals(name) || "content".equals(name)) {
21939                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
21940                        } else {
21941                            pw.println("Error: unknown resolver table type: " + name);
21942                            return;
21943                        }
21944                        opti++;
21945                    }
21946                }
21947            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
21948                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
21949            } else if ("permission".equals(cmd)) {
21950                if (opti >= args.length) {
21951                    pw.println("Error: permission requires permission name");
21952                    return;
21953                }
21954                permissionNames = new ArraySet<>();
21955                while (opti < args.length) {
21956                    permissionNames.add(args[opti]);
21957                    opti++;
21958                }
21959                dumpState.setDump(DumpState.DUMP_PERMISSIONS
21960                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
21961            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
21962                dumpState.setDump(DumpState.DUMP_PREFERRED);
21963            } else if ("preferred-xml".equals(cmd)) {
21964                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
21965                if (opti < args.length && "--full".equals(args[opti])) {
21966                    fullPreferred = true;
21967                    opti++;
21968                }
21969            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
21970                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
21971            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
21972                dumpState.setDump(DumpState.DUMP_PACKAGES);
21973            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
21974                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
21975            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
21976                dumpState.setDump(DumpState.DUMP_PROVIDERS);
21977            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
21978                dumpState.setDump(DumpState.DUMP_MESSAGES);
21979            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
21980                dumpState.setDump(DumpState.DUMP_VERIFIERS);
21981            } else if ("i".equals(cmd) || "ifv".equals(cmd)
21982                    || "intent-filter-verifiers".equals(cmd)) {
21983                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
21984            } else if ("version".equals(cmd)) {
21985                dumpState.setDump(DumpState.DUMP_VERSION);
21986            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
21987                dumpState.setDump(DumpState.DUMP_KEYSETS);
21988            } else if ("installs".equals(cmd)) {
21989                dumpState.setDump(DumpState.DUMP_INSTALLS);
21990            } else if ("frozen".equals(cmd)) {
21991                dumpState.setDump(DumpState.DUMP_FROZEN);
21992            } else if ("volumes".equals(cmd)) {
21993                dumpState.setDump(DumpState.DUMP_VOLUMES);
21994            } else if ("dexopt".equals(cmd)) {
21995                dumpState.setDump(DumpState.DUMP_DEXOPT);
21996            } else if ("compiler-stats".equals(cmd)) {
21997                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
21998            } else if ("changes".equals(cmd)) {
21999                dumpState.setDump(DumpState.DUMP_CHANGES);
22000            } else if ("write".equals(cmd)) {
22001                synchronized (mPackages) {
22002                    mSettings.writeLPr();
22003                    pw.println("Settings written.");
22004                    return;
22005                }
22006            }
22007        }
22008
22009        if (checkin) {
22010            pw.println("vers,1");
22011        }
22012
22013        // reader
22014        synchronized (mPackages) {
22015            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
22016                if (!checkin) {
22017                    if (dumpState.onTitlePrinted())
22018                        pw.println();
22019                    pw.println("Database versions:");
22020                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
22021                }
22022            }
22023
22024            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
22025                if (!checkin) {
22026                    if (dumpState.onTitlePrinted())
22027                        pw.println();
22028                    pw.println("Verifiers:");
22029                    pw.print("  Required: ");
22030                    pw.print(mRequiredVerifierPackage);
22031                    pw.print(" (uid=");
22032                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
22033                            UserHandle.USER_SYSTEM));
22034                    pw.println(")");
22035                } else if (mRequiredVerifierPackage != null) {
22036                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
22037                    pw.print(",");
22038                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
22039                            UserHandle.USER_SYSTEM));
22040                }
22041            }
22042
22043            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
22044                    packageName == null) {
22045                if (mIntentFilterVerifierComponent != null) {
22046                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
22047                    if (!checkin) {
22048                        if (dumpState.onTitlePrinted())
22049                            pw.println();
22050                        pw.println("Intent Filter Verifier:");
22051                        pw.print("  Using: ");
22052                        pw.print(verifierPackageName);
22053                        pw.print(" (uid=");
22054                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
22055                                UserHandle.USER_SYSTEM));
22056                        pw.println(")");
22057                    } else if (verifierPackageName != null) {
22058                        pw.print("ifv,"); pw.print(verifierPackageName);
22059                        pw.print(",");
22060                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
22061                                UserHandle.USER_SYSTEM));
22062                    }
22063                } else {
22064                    pw.println();
22065                    pw.println("No Intent Filter Verifier available!");
22066                }
22067            }
22068
22069            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
22070                boolean printedHeader = false;
22071                final Iterator<String> it = mSharedLibraries.keySet().iterator();
22072                while (it.hasNext()) {
22073                    String libName = it.next();
22074                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
22075                    if (versionedLib == null) {
22076                        continue;
22077                    }
22078                    final int versionCount = versionedLib.size();
22079                    for (int i = 0; i < versionCount; i++) {
22080                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
22081                        if (!checkin) {
22082                            if (!printedHeader) {
22083                                if (dumpState.onTitlePrinted())
22084                                    pw.println();
22085                                pw.println("Libraries:");
22086                                printedHeader = true;
22087                            }
22088                            pw.print("  ");
22089                        } else {
22090                            pw.print("lib,");
22091                        }
22092                        pw.print(libEntry.info.getName());
22093                        if (libEntry.info.isStatic()) {
22094                            pw.print(" version=" + libEntry.info.getVersion());
22095                        }
22096                        if (!checkin) {
22097                            pw.print(" -> ");
22098                        }
22099                        if (libEntry.path != null) {
22100                            pw.print(" (jar) ");
22101                            pw.print(libEntry.path);
22102                        } else {
22103                            pw.print(" (apk) ");
22104                            pw.print(libEntry.apk);
22105                        }
22106                        pw.println();
22107                    }
22108                }
22109            }
22110
22111            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
22112                if (dumpState.onTitlePrinted())
22113                    pw.println();
22114                if (!checkin) {
22115                    pw.println("Features:");
22116                }
22117
22118                synchronized (mAvailableFeatures) {
22119                    for (FeatureInfo feat : mAvailableFeatures.values()) {
22120                        if (checkin) {
22121                            pw.print("feat,");
22122                            pw.print(feat.name);
22123                            pw.print(",");
22124                            pw.println(feat.version);
22125                        } else {
22126                            pw.print("  ");
22127                            pw.print(feat.name);
22128                            if (feat.version > 0) {
22129                                pw.print(" version=");
22130                                pw.print(feat.version);
22131                            }
22132                            pw.println();
22133                        }
22134                    }
22135                }
22136            }
22137
22138            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
22139                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
22140                        : "Activity Resolver Table:", "  ", packageName,
22141                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22142                    dumpState.setTitlePrinted(true);
22143                }
22144            }
22145            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
22146                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
22147                        : "Receiver Resolver Table:", "  ", packageName,
22148                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22149                    dumpState.setTitlePrinted(true);
22150                }
22151            }
22152            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
22153                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
22154                        : "Service Resolver Table:", "  ", packageName,
22155                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22156                    dumpState.setTitlePrinted(true);
22157                }
22158            }
22159            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
22160                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
22161                        : "Provider Resolver Table:", "  ", packageName,
22162                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22163                    dumpState.setTitlePrinted(true);
22164                }
22165            }
22166
22167            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
22168                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
22169                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
22170                    int user = mSettings.mPreferredActivities.keyAt(i);
22171                    if (pir.dump(pw,
22172                            dumpState.getTitlePrinted()
22173                                ? "\nPreferred Activities User " + user + ":"
22174                                : "Preferred Activities User " + user + ":", "  ",
22175                            packageName, true, false)) {
22176                        dumpState.setTitlePrinted(true);
22177                    }
22178                }
22179            }
22180
22181            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
22182                pw.flush();
22183                FileOutputStream fout = new FileOutputStream(fd);
22184                BufferedOutputStream str = new BufferedOutputStream(fout);
22185                XmlSerializer serializer = new FastXmlSerializer();
22186                try {
22187                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
22188                    serializer.startDocument(null, true);
22189                    serializer.setFeature(
22190                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
22191                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
22192                    serializer.endDocument();
22193                    serializer.flush();
22194                } catch (IllegalArgumentException e) {
22195                    pw.println("Failed writing: " + e);
22196                } catch (IllegalStateException e) {
22197                    pw.println("Failed writing: " + e);
22198                } catch (IOException e) {
22199                    pw.println("Failed writing: " + e);
22200                }
22201            }
22202
22203            if (!checkin
22204                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
22205                    && packageName == null) {
22206                pw.println();
22207                int count = mSettings.mPackages.size();
22208                if (count == 0) {
22209                    pw.println("No applications!");
22210                    pw.println();
22211                } else {
22212                    final String prefix = "  ";
22213                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
22214                    if (allPackageSettings.size() == 0) {
22215                        pw.println("No domain preferred apps!");
22216                        pw.println();
22217                    } else {
22218                        pw.println("App verification status:");
22219                        pw.println();
22220                        count = 0;
22221                        for (PackageSetting ps : allPackageSettings) {
22222                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
22223                            if (ivi == null || ivi.getPackageName() == null) continue;
22224                            pw.println(prefix + "Package: " + ivi.getPackageName());
22225                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
22226                            pw.println(prefix + "Status:  " + ivi.getStatusString());
22227                            pw.println();
22228                            count++;
22229                        }
22230                        if (count == 0) {
22231                            pw.println(prefix + "No app verification established.");
22232                            pw.println();
22233                        }
22234                        for (int userId : sUserManager.getUserIds()) {
22235                            pw.println("App linkages for user " + userId + ":");
22236                            pw.println();
22237                            count = 0;
22238                            for (PackageSetting ps : allPackageSettings) {
22239                                final long status = ps.getDomainVerificationStatusForUser(userId);
22240                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
22241                                        && !DEBUG_DOMAIN_VERIFICATION) {
22242                                    continue;
22243                                }
22244                                pw.println(prefix + "Package: " + ps.name);
22245                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
22246                                String statusStr = IntentFilterVerificationInfo.
22247                                        getStatusStringFromValue(status);
22248                                pw.println(prefix + "Status:  " + statusStr);
22249                                pw.println();
22250                                count++;
22251                            }
22252                            if (count == 0) {
22253                                pw.println(prefix + "No configured app linkages.");
22254                                pw.println();
22255                            }
22256                        }
22257                    }
22258                }
22259            }
22260
22261            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
22262                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
22263                if (packageName == null && permissionNames == null) {
22264                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
22265                        if (iperm == 0) {
22266                            if (dumpState.onTitlePrinted())
22267                                pw.println();
22268                            pw.println("AppOp Permissions:");
22269                        }
22270                        pw.print("  AppOp Permission ");
22271                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
22272                        pw.println(":");
22273                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
22274                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
22275                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
22276                        }
22277                    }
22278                }
22279            }
22280
22281            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
22282                boolean printedSomething = false;
22283                for (PackageParser.Provider p : mProviders.mProviders.values()) {
22284                    if (packageName != null && !packageName.equals(p.info.packageName)) {
22285                        continue;
22286                    }
22287                    if (!printedSomething) {
22288                        if (dumpState.onTitlePrinted())
22289                            pw.println();
22290                        pw.println("Registered ContentProviders:");
22291                        printedSomething = true;
22292                    }
22293                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
22294                    pw.print("    "); pw.println(p.toString());
22295                }
22296                printedSomething = false;
22297                for (Map.Entry<String, PackageParser.Provider> entry :
22298                        mProvidersByAuthority.entrySet()) {
22299                    PackageParser.Provider p = entry.getValue();
22300                    if (packageName != null && !packageName.equals(p.info.packageName)) {
22301                        continue;
22302                    }
22303                    if (!printedSomething) {
22304                        if (dumpState.onTitlePrinted())
22305                            pw.println();
22306                        pw.println("ContentProvider Authorities:");
22307                        printedSomething = true;
22308                    }
22309                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
22310                    pw.print("    "); pw.println(p.toString());
22311                    if (p.info != null && p.info.applicationInfo != null) {
22312                        final String appInfo = p.info.applicationInfo.toString();
22313                        pw.print("      applicationInfo="); pw.println(appInfo);
22314                    }
22315                }
22316            }
22317
22318            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
22319                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
22320            }
22321
22322            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
22323                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
22324            }
22325
22326            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
22327                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
22328            }
22329
22330            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
22331                if (dumpState.onTitlePrinted()) pw.println();
22332                pw.println("Package Changes:");
22333                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
22334                final int K = mChangedPackages.size();
22335                for (int i = 0; i < K; i++) {
22336                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
22337                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
22338                    final int N = changes.size();
22339                    if (N == 0) {
22340                        pw.print("    "); pw.println("No packages changed");
22341                    } else {
22342                        for (int j = 0; j < N; j++) {
22343                            final String pkgName = changes.valueAt(j);
22344                            final int sequenceNumber = changes.keyAt(j);
22345                            pw.print("    ");
22346                            pw.print("seq=");
22347                            pw.print(sequenceNumber);
22348                            pw.print(", package=");
22349                            pw.println(pkgName);
22350                        }
22351                    }
22352                }
22353            }
22354
22355            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
22356                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
22357            }
22358
22359            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
22360                // XXX should handle packageName != null by dumping only install data that
22361                // the given package is involved with.
22362                if (dumpState.onTitlePrinted()) pw.println();
22363
22364                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22365                ipw.println();
22366                ipw.println("Frozen packages:");
22367                ipw.increaseIndent();
22368                if (mFrozenPackages.size() == 0) {
22369                    ipw.println("(none)");
22370                } else {
22371                    for (int i = 0; i < mFrozenPackages.size(); i++) {
22372                        ipw.println(mFrozenPackages.valueAt(i));
22373                    }
22374                }
22375                ipw.decreaseIndent();
22376            }
22377
22378            if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) {
22379                if (dumpState.onTitlePrinted()) pw.println();
22380
22381                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22382                ipw.println();
22383                ipw.println("Loaded volumes:");
22384                ipw.increaseIndent();
22385                if (mLoadedVolumes.size() == 0) {
22386                    ipw.println("(none)");
22387                } else {
22388                    for (int i = 0; i < mLoadedVolumes.size(); i++) {
22389                        ipw.println(mLoadedVolumes.valueAt(i));
22390                    }
22391                }
22392                ipw.decreaseIndent();
22393            }
22394
22395            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
22396                if (dumpState.onTitlePrinted()) pw.println();
22397                dumpDexoptStateLPr(pw, packageName);
22398            }
22399
22400            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
22401                if (dumpState.onTitlePrinted()) pw.println();
22402                dumpCompilerStatsLPr(pw, packageName);
22403            }
22404
22405            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
22406                if (dumpState.onTitlePrinted()) pw.println();
22407                mSettings.dumpReadMessagesLPr(pw, dumpState);
22408
22409                pw.println();
22410                pw.println("Package warning messages:");
22411                BufferedReader in = null;
22412                String line = null;
22413                try {
22414                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22415                    while ((line = in.readLine()) != null) {
22416                        if (line.contains("ignored: updated version")) continue;
22417                        pw.println(line);
22418                    }
22419                } catch (IOException ignored) {
22420                } finally {
22421                    IoUtils.closeQuietly(in);
22422                }
22423            }
22424
22425            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
22426                BufferedReader in = null;
22427                String line = null;
22428                try {
22429                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22430                    while ((line = in.readLine()) != null) {
22431                        if (line.contains("ignored: updated version")) continue;
22432                        pw.print("msg,");
22433                        pw.println(line);
22434                    }
22435                } catch (IOException ignored) {
22436                } finally {
22437                    IoUtils.closeQuietly(in);
22438                }
22439            }
22440        }
22441
22442        // PackageInstaller should be called outside of mPackages lock
22443        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
22444            // XXX should handle packageName != null by dumping only install data that
22445            // the given package is involved with.
22446            if (dumpState.onTitlePrinted()) pw.println();
22447            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
22448        }
22449    }
22450
22451    private void dumpProto(FileDescriptor fd) {
22452        final ProtoOutputStream proto = new ProtoOutputStream(fd);
22453
22454        synchronized (mPackages) {
22455            final long requiredVerifierPackageToken =
22456                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
22457            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
22458            proto.write(
22459                    PackageServiceDumpProto.PackageShortProto.UID,
22460                    getPackageUid(
22461                            mRequiredVerifierPackage,
22462                            MATCH_DEBUG_TRIAGED_MISSING,
22463                            UserHandle.USER_SYSTEM));
22464            proto.end(requiredVerifierPackageToken);
22465
22466            if (mIntentFilterVerifierComponent != null) {
22467                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
22468                final long verifierPackageToken =
22469                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
22470                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
22471                proto.write(
22472                        PackageServiceDumpProto.PackageShortProto.UID,
22473                        getPackageUid(
22474                                verifierPackageName,
22475                                MATCH_DEBUG_TRIAGED_MISSING,
22476                                UserHandle.USER_SYSTEM));
22477                proto.end(verifierPackageToken);
22478            }
22479
22480            dumpSharedLibrariesProto(proto);
22481            dumpFeaturesProto(proto);
22482            mSettings.dumpPackagesProto(proto);
22483            mSettings.dumpSharedUsersProto(proto);
22484            dumpMessagesProto(proto);
22485        }
22486        proto.flush();
22487    }
22488
22489    private void dumpMessagesProto(ProtoOutputStream proto) {
22490        BufferedReader in = null;
22491        String line = null;
22492        try {
22493            in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22494            while ((line = in.readLine()) != null) {
22495                if (line.contains("ignored: updated version")) continue;
22496                proto.write(PackageServiceDumpProto.MESSAGES, line);
22497            }
22498        } catch (IOException ignored) {
22499        } finally {
22500            IoUtils.closeQuietly(in);
22501        }
22502    }
22503
22504    private void dumpFeaturesProto(ProtoOutputStream proto) {
22505        synchronized (mAvailableFeatures) {
22506            final int count = mAvailableFeatures.size();
22507            for (int i = 0; i < count; i++) {
22508                final FeatureInfo feat = mAvailableFeatures.valueAt(i);
22509                final long featureToken = proto.start(PackageServiceDumpProto.FEATURES);
22510                proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name);
22511                proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version);
22512                proto.end(featureToken);
22513            }
22514        }
22515    }
22516
22517    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
22518        final int count = mSharedLibraries.size();
22519        for (int i = 0; i < count; i++) {
22520            final String libName = mSharedLibraries.keyAt(i);
22521            SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
22522            if (versionedLib == null) {
22523                continue;
22524            }
22525            final int versionCount = versionedLib.size();
22526            for (int j = 0; j < versionCount; j++) {
22527                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
22528                final long sharedLibraryToken =
22529                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
22530                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
22531                final boolean isJar = (libEntry.path != null);
22532                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
22533                if (isJar) {
22534                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
22535                } else {
22536                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
22537                }
22538                proto.end(sharedLibraryToken);
22539            }
22540        }
22541    }
22542
22543    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
22544        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22545        ipw.println();
22546        ipw.println("Dexopt state:");
22547        ipw.increaseIndent();
22548        Collection<PackageParser.Package> packages = null;
22549        if (packageName != null) {
22550            PackageParser.Package targetPackage = mPackages.get(packageName);
22551            if (targetPackage != null) {
22552                packages = Collections.singletonList(targetPackage);
22553            } else {
22554                ipw.println("Unable to find package: " + packageName);
22555                return;
22556            }
22557        } else {
22558            packages = mPackages.values();
22559        }
22560
22561        for (PackageParser.Package pkg : packages) {
22562            ipw.println("[" + pkg.packageName + "]");
22563            ipw.increaseIndent();
22564            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
22565            ipw.decreaseIndent();
22566        }
22567    }
22568
22569    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
22570        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22571        ipw.println();
22572        ipw.println("Compiler stats:");
22573        ipw.increaseIndent();
22574        Collection<PackageParser.Package> packages = null;
22575        if (packageName != null) {
22576            PackageParser.Package targetPackage = mPackages.get(packageName);
22577            if (targetPackage != null) {
22578                packages = Collections.singletonList(targetPackage);
22579            } else {
22580                ipw.println("Unable to find package: " + packageName);
22581                return;
22582            }
22583        } else {
22584            packages = mPackages.values();
22585        }
22586
22587        for (PackageParser.Package pkg : packages) {
22588            ipw.println("[" + pkg.packageName + "]");
22589            ipw.increaseIndent();
22590
22591            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
22592            if (stats == null) {
22593                ipw.println("(No recorded stats)");
22594            } else {
22595                stats.dump(ipw);
22596            }
22597            ipw.decreaseIndent();
22598        }
22599    }
22600
22601    private String dumpDomainString(String packageName) {
22602        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
22603                .getList();
22604        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
22605
22606        ArraySet<String> result = new ArraySet<>();
22607        if (iviList.size() > 0) {
22608            for (IntentFilterVerificationInfo ivi : iviList) {
22609                for (String host : ivi.getDomains()) {
22610                    result.add(host);
22611                }
22612            }
22613        }
22614        if (filters != null && filters.size() > 0) {
22615            for (IntentFilter filter : filters) {
22616                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
22617                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
22618                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
22619                    result.addAll(filter.getHostsList());
22620                }
22621            }
22622        }
22623
22624        StringBuilder sb = new StringBuilder(result.size() * 16);
22625        for (String domain : result) {
22626            if (sb.length() > 0) sb.append(" ");
22627            sb.append(domain);
22628        }
22629        return sb.toString();
22630    }
22631
22632    // ------- apps on sdcard specific code -------
22633    static final boolean DEBUG_SD_INSTALL = false;
22634
22635    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
22636
22637    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
22638
22639    private boolean mMediaMounted = false;
22640
22641    static String getEncryptKey() {
22642        try {
22643            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
22644                    SD_ENCRYPTION_KEYSTORE_NAME);
22645            if (sdEncKey == null) {
22646                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
22647                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
22648                if (sdEncKey == null) {
22649                    Slog.e(TAG, "Failed to create encryption keys");
22650                    return null;
22651                }
22652            }
22653            return sdEncKey;
22654        } catch (NoSuchAlgorithmException nsae) {
22655            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
22656            return null;
22657        } catch (IOException ioe) {
22658            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
22659            return null;
22660        }
22661    }
22662
22663    /*
22664     * Update media status on PackageManager.
22665     */
22666    @Override
22667    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
22668        enforceSystemOrRoot("Media status can only be updated by the system");
22669        // reader; this apparently protects mMediaMounted, but should probably
22670        // be a different lock in that case.
22671        synchronized (mPackages) {
22672            Log.i(TAG, "Updating external media status from "
22673                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
22674                    + (mediaStatus ? "mounted" : "unmounted"));
22675            if (DEBUG_SD_INSTALL)
22676                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
22677                        + ", mMediaMounted=" + mMediaMounted);
22678            if (mediaStatus == mMediaMounted) {
22679                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
22680                        : 0, -1);
22681                mHandler.sendMessage(msg);
22682                return;
22683            }
22684            mMediaMounted = mediaStatus;
22685        }
22686        // Queue up an async operation since the package installation may take a
22687        // little while.
22688        mHandler.post(new Runnable() {
22689            public void run() {
22690                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
22691            }
22692        });
22693    }
22694
22695    /**
22696     * Called by StorageManagerService when the initial ASECs to scan are available.
22697     * Should block until all the ASEC containers are finished being scanned.
22698     */
22699    public void scanAvailableAsecs() {
22700        updateExternalMediaStatusInner(true, false, false);
22701    }
22702
22703    /*
22704     * Collect information of applications on external media, map them against
22705     * existing containers and update information based on current mount status.
22706     * Please note that we always have to report status if reportStatus has been
22707     * set to true especially when unloading packages.
22708     */
22709    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
22710            boolean externalStorage) {
22711        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
22712        int[] uidArr = EmptyArray.INT;
22713
22714        final String[] list = PackageHelper.getSecureContainerList();
22715        if (ArrayUtils.isEmpty(list)) {
22716            Log.i(TAG, "No secure containers found");
22717        } else {
22718            // Process list of secure containers and categorize them
22719            // as active or stale based on their package internal state.
22720
22721            // reader
22722            synchronized (mPackages) {
22723                for (String cid : list) {
22724                    // Leave stages untouched for now; installer service owns them
22725                    if (PackageInstallerService.isStageName(cid)) continue;
22726
22727                    if (DEBUG_SD_INSTALL)
22728                        Log.i(TAG, "Processing container " + cid);
22729                    String pkgName = getAsecPackageName(cid);
22730                    if (pkgName == null) {
22731                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
22732                        continue;
22733                    }
22734                    if (DEBUG_SD_INSTALL)
22735                        Log.i(TAG, "Looking for pkg : " + pkgName);
22736
22737                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
22738                    if (ps == null) {
22739                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
22740                        continue;
22741                    }
22742
22743                    /*
22744                     * Skip packages that are not external if we're unmounting
22745                     * external storage.
22746                     */
22747                    if (externalStorage && !isMounted && !isExternal(ps)) {
22748                        continue;
22749                    }
22750
22751                    final AsecInstallArgs args = new AsecInstallArgs(cid,
22752                            getAppDexInstructionSets(ps), ps.isForwardLocked());
22753                    // The package status is changed only if the code path
22754                    // matches between settings and the container id.
22755                    if (ps.codePathString != null
22756                            && ps.codePathString.startsWith(args.getCodePath())) {
22757                        if (DEBUG_SD_INSTALL) {
22758                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
22759                                    + " at code path: " + ps.codePathString);
22760                        }
22761
22762                        // We do have a valid package installed on sdcard
22763                        processCids.put(args, ps.codePathString);
22764                        final int uid = ps.appId;
22765                        if (uid != -1) {
22766                            uidArr = ArrayUtils.appendInt(uidArr, uid);
22767                        }
22768                    } else {
22769                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
22770                                + ps.codePathString);
22771                    }
22772                }
22773            }
22774
22775            Arrays.sort(uidArr);
22776        }
22777
22778        // Process packages with valid entries.
22779        if (isMounted) {
22780            if (DEBUG_SD_INSTALL)
22781                Log.i(TAG, "Loading packages");
22782            loadMediaPackages(processCids, uidArr, externalStorage);
22783            startCleaningPackages();
22784            mInstallerService.onSecureContainersAvailable();
22785        } else {
22786            if (DEBUG_SD_INSTALL)
22787                Log.i(TAG, "Unloading packages");
22788            unloadMediaPackages(processCids, uidArr, reportStatus);
22789        }
22790    }
22791
22792    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22793            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
22794        final int size = infos.size();
22795        final String[] packageNames = new String[size];
22796        final int[] packageUids = new int[size];
22797        for (int i = 0; i < size; i++) {
22798            final ApplicationInfo info = infos.get(i);
22799            packageNames[i] = info.packageName;
22800            packageUids[i] = info.uid;
22801        }
22802        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
22803                finishedReceiver);
22804    }
22805
22806    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22807            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
22808        sendResourcesChangedBroadcast(mediaStatus, replacing,
22809                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
22810    }
22811
22812    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22813            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
22814        int size = pkgList.length;
22815        if (size > 0) {
22816            // Send broadcasts here
22817            Bundle extras = new Bundle();
22818            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
22819            if (uidArr != null) {
22820                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
22821            }
22822            if (replacing) {
22823                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
22824            }
22825            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
22826                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
22827            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
22828        }
22829    }
22830
22831   /*
22832     * Look at potentially valid container ids from processCids If package
22833     * information doesn't match the one on record or package scanning fails,
22834     * the cid is added to list of removeCids. We currently don't delete stale
22835     * containers.
22836     */
22837    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
22838            boolean externalStorage) {
22839        ArrayList<String> pkgList = new ArrayList<String>();
22840        Set<AsecInstallArgs> keys = processCids.keySet();
22841
22842        for (AsecInstallArgs args : keys) {
22843            String codePath = processCids.get(args);
22844            if (DEBUG_SD_INSTALL)
22845                Log.i(TAG, "Loading container : " + args.cid);
22846            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
22847            try {
22848                // Make sure there are no container errors first.
22849                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
22850                    Slog.e(TAG, "Failed to mount cid : " + args.cid
22851                            + " when installing from sdcard");
22852                    continue;
22853                }
22854                // Check code path here.
22855                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
22856                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
22857                            + " does not match one in settings " + codePath);
22858                    continue;
22859                }
22860                // Parse package
22861                int parseFlags = mDefParseFlags;
22862                if (args.isExternalAsec()) {
22863                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
22864                }
22865                if (args.isFwdLocked()) {
22866                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
22867                }
22868
22869                synchronized (mInstallLock) {
22870                    PackageParser.Package pkg = null;
22871                    try {
22872                        // Sadly we don't know the package name yet to freeze it
22873                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
22874                                SCAN_IGNORE_FROZEN, 0, null);
22875                    } catch (PackageManagerException e) {
22876                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
22877                    }
22878                    // Scan the package
22879                    if (pkg != null) {
22880                        /*
22881                         * TODO why is the lock being held? doPostInstall is
22882                         * called in other places without the lock. This needs
22883                         * to be straightened out.
22884                         */
22885                        // writer
22886                        synchronized (mPackages) {
22887                            retCode = PackageManager.INSTALL_SUCCEEDED;
22888                            pkgList.add(pkg.packageName);
22889                            // Post process args
22890                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
22891                                    pkg.applicationInfo.uid);
22892                        }
22893                    } else {
22894                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
22895                    }
22896                }
22897
22898            } finally {
22899                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
22900                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
22901                }
22902            }
22903        }
22904        // writer
22905        synchronized (mPackages) {
22906            // If the platform SDK has changed since the last time we booted,
22907            // we need to re-grant app permission to catch any new ones that
22908            // appear. This is really a hack, and means that apps can in some
22909            // cases get permissions that the user didn't initially explicitly
22910            // allow... it would be nice to have some better way to handle
22911            // this situation.
22912            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
22913                    : mSettings.getInternalVersion();
22914            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
22915                    : StorageManager.UUID_PRIVATE_INTERNAL;
22916
22917            int updateFlags = UPDATE_PERMISSIONS_ALL;
22918            if (ver.sdkVersion != mSdkVersion) {
22919                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
22920                        + mSdkVersion + "; regranting permissions for external");
22921                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
22922            }
22923            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
22924
22925            // Yay, everything is now upgraded
22926            ver.forceCurrent();
22927
22928            // can downgrade to reader
22929            // Persist settings
22930            mSettings.writeLPr();
22931        }
22932        // Send a broadcast to let everyone know we are done processing
22933        if (pkgList.size() > 0) {
22934            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
22935        }
22936    }
22937
22938   /*
22939     * Utility method to unload a list of specified containers
22940     */
22941    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
22942        // Just unmount all valid containers.
22943        for (AsecInstallArgs arg : cidArgs) {
22944            synchronized (mInstallLock) {
22945                arg.doPostDeleteLI(false);
22946           }
22947       }
22948   }
22949
22950    /*
22951     * Unload packages mounted on external media. This involves deleting package
22952     * data from internal structures, sending broadcasts about disabled packages,
22953     * gc'ing to free up references, unmounting all secure containers
22954     * corresponding to packages on external media, and posting a
22955     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
22956     * that we always have to post this message if status has been requested no
22957     * matter what.
22958     */
22959    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
22960            final boolean reportStatus) {
22961        if (DEBUG_SD_INSTALL)
22962            Log.i(TAG, "unloading media packages");
22963        ArrayList<String> pkgList = new ArrayList<String>();
22964        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
22965        final Set<AsecInstallArgs> keys = processCids.keySet();
22966        for (AsecInstallArgs args : keys) {
22967            String pkgName = args.getPackageName();
22968            if (DEBUG_SD_INSTALL)
22969                Log.i(TAG, "Trying to unload pkg : " + pkgName);
22970            // Delete package internally
22971            PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
22972            synchronized (mInstallLock) {
22973                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
22974                final boolean res;
22975                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
22976                        "unloadMediaPackages")) {
22977                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
22978                            null);
22979                }
22980                if (res) {
22981                    pkgList.add(pkgName);
22982                } else {
22983                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
22984                    failedList.add(args);
22985                }
22986            }
22987        }
22988
22989        // reader
22990        synchronized (mPackages) {
22991            // We didn't update the settings after removing each package;
22992            // write them now for all packages.
22993            mSettings.writeLPr();
22994        }
22995
22996        // We have to absolutely send UPDATED_MEDIA_STATUS only
22997        // after confirming that all the receivers processed the ordered
22998        // broadcast when packages get disabled, force a gc to clean things up.
22999        // and unload all the containers.
23000        if (pkgList.size() > 0) {
23001            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
23002                    new IIntentReceiver.Stub() {
23003                public void performReceive(Intent intent, int resultCode, String data,
23004                        Bundle extras, boolean ordered, boolean sticky,
23005                        int sendingUser) throws RemoteException {
23006                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
23007                            reportStatus ? 1 : 0, 1, keys);
23008                    mHandler.sendMessage(msg);
23009                }
23010            });
23011        } else {
23012            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
23013                    keys);
23014            mHandler.sendMessage(msg);
23015        }
23016    }
23017
23018    private void loadPrivatePackages(final VolumeInfo vol) {
23019        mHandler.post(new Runnable() {
23020            @Override
23021            public void run() {
23022                loadPrivatePackagesInner(vol);
23023            }
23024        });
23025    }
23026
23027    private void loadPrivatePackagesInner(VolumeInfo vol) {
23028        final String volumeUuid = vol.fsUuid;
23029        if (TextUtils.isEmpty(volumeUuid)) {
23030            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
23031            return;
23032        }
23033
23034        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
23035        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
23036        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
23037
23038        final VersionInfo ver;
23039        final List<PackageSetting> packages;
23040        synchronized (mPackages) {
23041            ver = mSettings.findOrCreateVersion(volumeUuid);
23042            packages = mSettings.getVolumePackagesLPr(volumeUuid);
23043        }
23044
23045        for (PackageSetting ps : packages) {
23046            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
23047            synchronized (mInstallLock) {
23048                final PackageParser.Package pkg;
23049                try {
23050                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
23051                    loaded.add(pkg.applicationInfo);
23052
23053                } catch (PackageManagerException e) {
23054                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
23055                }
23056
23057                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
23058                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
23059                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
23060                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
23061                }
23062            }
23063        }
23064
23065        // Reconcile app data for all started/unlocked users
23066        final StorageManager sm = mContext.getSystemService(StorageManager.class);
23067        final UserManager um = mContext.getSystemService(UserManager.class);
23068        UserManagerInternal umInternal = getUserManagerInternal();
23069        for (UserInfo user : um.getUsers()) {
23070            final int flags;
23071            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
23072                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
23073            } else if (umInternal.isUserRunning(user.id)) {
23074                flags = StorageManager.FLAG_STORAGE_DE;
23075            } else {
23076                continue;
23077            }
23078
23079            try {
23080                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
23081                synchronized (mInstallLock) {
23082                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
23083                }
23084            } catch (IllegalStateException e) {
23085                // Device was probably ejected, and we'll process that event momentarily
23086                Slog.w(TAG, "Failed to prepare storage: " + e);
23087            }
23088        }
23089
23090        synchronized (mPackages) {
23091            int updateFlags = UPDATE_PERMISSIONS_ALL;
23092            if (ver.sdkVersion != mSdkVersion) {
23093                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
23094                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
23095                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
23096            }
23097            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
23098
23099            // Yay, everything is now upgraded
23100            ver.forceCurrent();
23101
23102            mSettings.writeLPr();
23103        }
23104
23105        for (PackageFreezer freezer : freezers) {
23106            freezer.close();
23107        }
23108
23109        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
23110        sendResourcesChangedBroadcast(true, false, loaded, null);
23111        mLoadedVolumes.add(vol.getId());
23112    }
23113
23114    private void unloadPrivatePackages(final VolumeInfo vol) {
23115        mHandler.post(new Runnable() {
23116            @Override
23117            public void run() {
23118                unloadPrivatePackagesInner(vol);
23119            }
23120        });
23121    }
23122
23123    private void unloadPrivatePackagesInner(VolumeInfo vol) {
23124        final String volumeUuid = vol.fsUuid;
23125        if (TextUtils.isEmpty(volumeUuid)) {
23126            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
23127            return;
23128        }
23129
23130        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
23131        synchronized (mInstallLock) {
23132        synchronized (mPackages) {
23133            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
23134            for (PackageSetting ps : packages) {
23135                if (ps.pkg == null) continue;
23136
23137                final ApplicationInfo info = ps.pkg.applicationInfo;
23138                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
23139                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
23140
23141                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
23142                        "unloadPrivatePackagesInner")) {
23143                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
23144                            false, null)) {
23145                        unloaded.add(info);
23146                    } else {
23147                        Slog.w(TAG, "Failed to unload " + ps.codePath);
23148                    }
23149                }
23150
23151                // Try very hard to release any references to this package
23152                // so we don't risk the system server being killed due to
23153                // open FDs
23154                AttributeCache.instance().removePackage(ps.name);
23155            }
23156
23157            mSettings.writeLPr();
23158        }
23159        }
23160
23161        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
23162        sendResourcesChangedBroadcast(false, false, unloaded, null);
23163        mLoadedVolumes.remove(vol.getId());
23164
23165        // Try very hard to release any references to this path so we don't risk
23166        // the system server being killed due to open FDs
23167        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
23168
23169        for (int i = 0; i < 3; i++) {
23170            System.gc();
23171            System.runFinalization();
23172        }
23173    }
23174
23175    private void assertPackageKnown(String volumeUuid, String packageName)
23176            throws PackageManagerException {
23177        synchronized (mPackages) {
23178            // Normalize package name to handle renamed packages
23179            packageName = normalizePackageNameLPr(packageName);
23180
23181            final PackageSetting ps = mSettings.mPackages.get(packageName);
23182            if (ps == null) {
23183                throw new PackageManagerException("Package " + packageName + " is unknown");
23184            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23185                throw new PackageManagerException(
23186                        "Package " + packageName + " found on unknown volume " + volumeUuid
23187                                + "; expected volume " + ps.volumeUuid);
23188            }
23189        }
23190    }
23191
23192    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
23193            throws PackageManagerException {
23194        synchronized (mPackages) {
23195            // Normalize package name to handle renamed packages
23196            packageName = normalizePackageNameLPr(packageName);
23197
23198            final PackageSetting ps = mSettings.mPackages.get(packageName);
23199            if (ps == null) {
23200                throw new PackageManagerException("Package " + packageName + " is unknown");
23201            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23202                throw new PackageManagerException(
23203                        "Package " + packageName + " found on unknown volume " + volumeUuid
23204                                + "; expected volume " + ps.volumeUuid);
23205            } else if (!ps.getInstalled(userId)) {
23206                throw new PackageManagerException(
23207                        "Package " + packageName + " not installed for user " + userId);
23208            }
23209        }
23210    }
23211
23212    private List<String> collectAbsoluteCodePaths() {
23213        synchronized (mPackages) {
23214            List<String> codePaths = new ArrayList<>();
23215            final int packageCount = mSettings.mPackages.size();
23216            for (int i = 0; i < packageCount; i++) {
23217                final PackageSetting ps = mSettings.mPackages.valueAt(i);
23218                codePaths.add(ps.codePath.getAbsolutePath());
23219            }
23220            return codePaths;
23221        }
23222    }
23223
23224    /**
23225     * Examine all apps present on given mounted volume, and destroy apps that
23226     * aren't expected, either due to uninstallation or reinstallation on
23227     * another volume.
23228     */
23229    private void reconcileApps(String volumeUuid) {
23230        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
23231        List<File> filesToDelete = null;
23232
23233        final File[] files = FileUtils.listFilesOrEmpty(
23234                Environment.getDataAppDirectory(volumeUuid));
23235        for (File file : files) {
23236            final boolean isPackage = (isApkFile(file) || file.isDirectory())
23237                    && !PackageInstallerService.isStageName(file.getName());
23238            if (!isPackage) {
23239                // Ignore entries which are not packages
23240                continue;
23241            }
23242
23243            String absolutePath = file.getAbsolutePath();
23244
23245            boolean pathValid = false;
23246            final int absoluteCodePathCount = absoluteCodePaths.size();
23247            for (int i = 0; i < absoluteCodePathCount; i++) {
23248                String absoluteCodePath = absoluteCodePaths.get(i);
23249                if (absolutePath.startsWith(absoluteCodePath)) {
23250                    pathValid = true;
23251                    break;
23252                }
23253            }
23254
23255            if (!pathValid) {
23256                if (filesToDelete == null) {
23257                    filesToDelete = new ArrayList<>();
23258                }
23259                filesToDelete.add(file);
23260            }
23261        }
23262
23263        if (filesToDelete != null) {
23264            final int fileToDeleteCount = filesToDelete.size();
23265            for (int i = 0; i < fileToDeleteCount; i++) {
23266                File fileToDelete = filesToDelete.get(i);
23267                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
23268                synchronized (mInstallLock) {
23269                    removeCodePathLI(fileToDelete);
23270                }
23271            }
23272        }
23273    }
23274
23275    /**
23276     * Reconcile all app data for the given user.
23277     * <p>
23278     * Verifies that directories exist and that ownership and labeling is
23279     * correct for all installed apps on all mounted volumes.
23280     */
23281    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
23282        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23283        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
23284            final String volumeUuid = vol.getFsUuid();
23285            synchronized (mInstallLock) {
23286                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
23287            }
23288        }
23289    }
23290
23291    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23292            boolean migrateAppData) {
23293        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
23294    }
23295
23296    /**
23297     * Reconcile all app data on given mounted volume.
23298     * <p>
23299     * Destroys app data that isn't expected, either due to uninstallation or
23300     * reinstallation on another volume.
23301     * <p>
23302     * Verifies that directories exist and that ownership and labeling is
23303     * correct for all installed apps.
23304     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
23305     */
23306    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23307            boolean migrateAppData, boolean onlyCoreApps) {
23308        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
23309                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
23310        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
23311
23312        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
23313        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
23314
23315        // First look for stale data that doesn't belong, and check if things
23316        // have changed since we did our last restorecon
23317        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
23318            if (StorageManager.isFileEncryptedNativeOrEmulated()
23319                    && !StorageManager.isUserKeyUnlocked(userId)) {
23320                throw new RuntimeException(
23321                        "Yikes, someone asked us to reconcile CE storage while " + userId
23322                                + " was still locked; this would have caused massive data loss!");
23323            }
23324
23325            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
23326            for (File file : files) {
23327                final String packageName = file.getName();
23328                try {
23329                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
23330                } catch (PackageManagerException e) {
23331                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
23332                    try {
23333                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
23334                                StorageManager.FLAG_STORAGE_CE, 0);
23335                    } catch (InstallerException e2) {
23336                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
23337                    }
23338                }
23339            }
23340        }
23341        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
23342            final File[] files = FileUtils.listFilesOrEmpty(deDir);
23343            for (File file : files) {
23344                final String packageName = file.getName();
23345                try {
23346                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
23347                } catch (PackageManagerException e) {
23348                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
23349                    try {
23350                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
23351                                StorageManager.FLAG_STORAGE_DE, 0);
23352                    } catch (InstallerException e2) {
23353                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
23354                    }
23355                }
23356            }
23357        }
23358
23359        // Ensure that data directories are ready to roll for all packages
23360        // installed for this volume and user
23361        final List<PackageSetting> packages;
23362        synchronized (mPackages) {
23363            packages = mSettings.getVolumePackagesLPr(volumeUuid);
23364        }
23365        int preparedCount = 0;
23366        for (PackageSetting ps : packages) {
23367            final String packageName = ps.name;
23368            if (ps.pkg == null) {
23369                Slog.w(TAG, "Odd, missing scanned package " + packageName);
23370                // TODO: might be due to legacy ASEC apps; we should circle back
23371                // and reconcile again once they're scanned
23372                continue;
23373            }
23374            // Skip non-core apps if requested
23375            if (onlyCoreApps && !ps.pkg.coreApp) {
23376                result.add(packageName);
23377                continue;
23378            }
23379
23380            if (ps.getInstalled(userId)) {
23381                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
23382                preparedCount++;
23383            }
23384        }
23385
23386        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
23387        return result;
23388    }
23389
23390    /**
23391     * Prepare app data for the given app just after it was installed or
23392     * upgraded. This method carefully only touches users that it's installed
23393     * for, and it forces a restorecon to handle any seinfo changes.
23394     * <p>
23395     * Verifies that directories exist and that ownership and labeling is
23396     * correct for all installed apps. If there is an ownership mismatch, it
23397     * will try recovering system apps by wiping data; third-party app data is
23398     * left intact.
23399     * <p>
23400     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
23401     */
23402    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
23403        final PackageSetting ps;
23404        synchronized (mPackages) {
23405            ps = mSettings.mPackages.get(pkg.packageName);
23406            mSettings.writeKernelMappingLPr(ps);
23407        }
23408
23409        final UserManager um = mContext.getSystemService(UserManager.class);
23410        UserManagerInternal umInternal = getUserManagerInternal();
23411        for (UserInfo user : um.getUsers()) {
23412            final int flags;
23413            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
23414                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
23415            } else if (umInternal.isUserRunning(user.id)) {
23416                flags = StorageManager.FLAG_STORAGE_DE;
23417            } else {
23418                continue;
23419            }
23420
23421            if (ps.getInstalled(user.id)) {
23422                // TODO: when user data is locked, mark that we're still dirty
23423                prepareAppDataLIF(pkg, user.id, flags);
23424            }
23425        }
23426    }
23427
23428    /**
23429     * Prepare app data for the given app.
23430     * <p>
23431     * Verifies that directories exist and that ownership and labeling is
23432     * correct for all installed apps. If there is an ownership mismatch, this
23433     * will try recovering system apps by wiping data; third-party app data is
23434     * left intact.
23435     */
23436    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
23437        if (pkg == null) {
23438            Slog.wtf(TAG, "Package was null!", new Throwable());
23439            return;
23440        }
23441        prepareAppDataLeafLIF(pkg, userId, flags);
23442        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
23443        for (int i = 0; i < childCount; i++) {
23444            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
23445        }
23446    }
23447
23448    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
23449            boolean maybeMigrateAppData) {
23450        prepareAppDataLIF(pkg, userId, flags);
23451
23452        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
23453            // We may have just shuffled around app data directories, so
23454            // prepare them one more time
23455            prepareAppDataLIF(pkg, userId, flags);
23456        }
23457    }
23458
23459    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
23460        if (DEBUG_APP_DATA) {
23461            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
23462                    + Integer.toHexString(flags));
23463        }
23464
23465        final String volumeUuid = pkg.volumeUuid;
23466        final String packageName = pkg.packageName;
23467        final ApplicationInfo app = pkg.applicationInfo;
23468        final int appId = UserHandle.getAppId(app.uid);
23469
23470        Preconditions.checkNotNull(app.seInfo);
23471
23472        long ceDataInode = -1;
23473        try {
23474            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
23475                    appId, app.seInfo, app.targetSdkVersion);
23476        } catch (InstallerException e) {
23477            if (app.isSystemApp()) {
23478                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
23479                        + ", but trying to recover: " + e);
23480                destroyAppDataLeafLIF(pkg, userId, flags);
23481                try {
23482                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
23483                            appId, app.seInfo, app.targetSdkVersion);
23484                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
23485                } catch (InstallerException e2) {
23486                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
23487                }
23488            } else {
23489                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
23490            }
23491        }
23492
23493        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
23494            // TODO: mark this structure as dirty so we persist it!
23495            synchronized (mPackages) {
23496                final PackageSetting ps = mSettings.mPackages.get(packageName);
23497                if (ps != null) {
23498                    ps.setCeDataInode(ceDataInode, userId);
23499                }
23500            }
23501        }
23502
23503        prepareAppDataContentsLeafLIF(pkg, userId, flags);
23504    }
23505
23506    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
23507        if (pkg == null) {
23508            Slog.wtf(TAG, "Package was null!", new Throwable());
23509            return;
23510        }
23511        prepareAppDataContentsLeafLIF(pkg, userId, flags);
23512        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
23513        for (int i = 0; i < childCount; i++) {
23514            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
23515        }
23516    }
23517
23518    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
23519        final String volumeUuid = pkg.volumeUuid;
23520        final String packageName = pkg.packageName;
23521        final ApplicationInfo app = pkg.applicationInfo;
23522
23523        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
23524            // Create a native library symlink only if we have native libraries
23525            // and if the native libraries are 32 bit libraries. We do not provide
23526            // this symlink for 64 bit libraries.
23527            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
23528                final String nativeLibPath = app.nativeLibraryDir;
23529                try {
23530                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
23531                            nativeLibPath, userId);
23532                } catch (InstallerException e) {
23533                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
23534                }
23535            }
23536        }
23537    }
23538
23539    /**
23540     * For system apps on non-FBE devices, this method migrates any existing
23541     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
23542     * requested by the app.
23543     */
23544    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
23545        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
23546                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
23547            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
23548                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
23549            try {
23550                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
23551                        storageTarget);
23552            } catch (InstallerException e) {
23553                logCriticalInfo(Log.WARN,
23554                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
23555            }
23556            return true;
23557        } else {
23558            return false;
23559        }
23560    }
23561
23562    public PackageFreezer freezePackage(String packageName, String killReason) {
23563        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
23564    }
23565
23566    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
23567        return new PackageFreezer(packageName, userId, killReason);
23568    }
23569
23570    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
23571            String killReason) {
23572        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
23573    }
23574
23575    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
23576            String killReason) {
23577        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
23578            return new PackageFreezer();
23579        } else {
23580            return freezePackage(packageName, userId, killReason);
23581        }
23582    }
23583
23584    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
23585            String killReason) {
23586        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
23587    }
23588
23589    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
23590            String killReason) {
23591        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
23592            return new PackageFreezer();
23593        } else {
23594            return freezePackage(packageName, userId, killReason);
23595        }
23596    }
23597
23598    /**
23599     * Class that freezes and kills the given package upon creation, and
23600     * unfreezes it upon closing. This is typically used when doing surgery on
23601     * app code/data to prevent the app from running while you're working.
23602     */
23603    private class PackageFreezer implements AutoCloseable {
23604        private final String mPackageName;
23605        private final PackageFreezer[] mChildren;
23606
23607        private final boolean mWeFroze;
23608
23609        private final AtomicBoolean mClosed = new AtomicBoolean();
23610        private final CloseGuard mCloseGuard = CloseGuard.get();
23611
23612        /**
23613         * Create and return a stub freezer that doesn't actually do anything,
23614         * typically used when someone requested
23615         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
23616         * {@link PackageManager#DELETE_DONT_KILL_APP}.
23617         */
23618        public PackageFreezer() {
23619            mPackageName = null;
23620            mChildren = null;
23621            mWeFroze = false;
23622            mCloseGuard.open("close");
23623        }
23624
23625        public PackageFreezer(String packageName, int userId, String killReason) {
23626            synchronized (mPackages) {
23627                mPackageName = packageName;
23628                mWeFroze = mFrozenPackages.add(mPackageName);
23629
23630                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
23631                if (ps != null) {
23632                    killApplication(ps.name, ps.appId, userId, killReason);
23633                }
23634
23635                final PackageParser.Package p = mPackages.get(packageName);
23636                if (p != null && p.childPackages != null) {
23637                    final int N = p.childPackages.size();
23638                    mChildren = new PackageFreezer[N];
23639                    for (int i = 0; i < N; i++) {
23640                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
23641                                userId, killReason);
23642                    }
23643                } else {
23644                    mChildren = null;
23645                }
23646            }
23647            mCloseGuard.open("close");
23648        }
23649
23650        @Override
23651        protected void finalize() throws Throwable {
23652            try {
23653                if (mCloseGuard != null) {
23654                    mCloseGuard.warnIfOpen();
23655                }
23656
23657                close();
23658            } finally {
23659                super.finalize();
23660            }
23661        }
23662
23663        @Override
23664        public void close() {
23665            mCloseGuard.close();
23666            if (mClosed.compareAndSet(false, true)) {
23667                synchronized (mPackages) {
23668                    if (mWeFroze) {
23669                        mFrozenPackages.remove(mPackageName);
23670                    }
23671
23672                    if (mChildren != null) {
23673                        for (PackageFreezer freezer : mChildren) {
23674                            freezer.close();
23675                        }
23676                    }
23677                }
23678            }
23679        }
23680    }
23681
23682    /**
23683     * Verify that given package is currently frozen.
23684     */
23685    private void checkPackageFrozen(String packageName) {
23686        synchronized (mPackages) {
23687            if (!mFrozenPackages.contains(packageName)) {
23688                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
23689            }
23690        }
23691    }
23692
23693    @Override
23694    public int movePackage(final String packageName, final String volumeUuid) {
23695        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
23696
23697        final int callingUid = Binder.getCallingUid();
23698        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
23699        final int moveId = mNextMoveId.getAndIncrement();
23700        mHandler.post(new Runnable() {
23701            @Override
23702            public void run() {
23703                try {
23704                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
23705                } catch (PackageManagerException e) {
23706                    Slog.w(TAG, "Failed to move " + packageName, e);
23707                    mMoveCallbacks.notifyStatusChanged(moveId, e.error);
23708                }
23709            }
23710        });
23711        return moveId;
23712    }
23713
23714    private void movePackageInternal(final String packageName, final String volumeUuid,
23715            final int moveId, final int callingUid, UserHandle user)
23716                    throws PackageManagerException {
23717        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23718        final PackageManager pm = mContext.getPackageManager();
23719
23720        final boolean currentAsec;
23721        final String currentVolumeUuid;
23722        final File codeFile;
23723        final String installerPackageName;
23724        final String packageAbiOverride;
23725        final int appId;
23726        final String seinfo;
23727        final String label;
23728        final int targetSdkVersion;
23729        final PackageFreezer freezer;
23730        final int[] installedUserIds;
23731
23732        // reader
23733        synchronized (mPackages) {
23734            final PackageParser.Package pkg = mPackages.get(packageName);
23735            final PackageSetting ps = mSettings.mPackages.get(packageName);
23736            if (pkg == null
23737                    || ps == null
23738                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
23739                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
23740            }
23741            if (pkg.applicationInfo.isSystemApp()) {
23742                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
23743                        "Cannot move system application");
23744            }
23745
23746            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
23747            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
23748                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
23749            if (isInternalStorage && !allow3rdPartyOnInternal) {
23750                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
23751                        "3rd party apps are not allowed on internal storage");
23752            }
23753
23754            if (pkg.applicationInfo.isExternalAsec()) {
23755                currentAsec = true;
23756                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
23757            } else if (pkg.applicationInfo.isForwardLocked()) {
23758                currentAsec = true;
23759                currentVolumeUuid = "forward_locked";
23760            } else {
23761                currentAsec = false;
23762                currentVolumeUuid = ps.volumeUuid;
23763
23764                final File probe = new File(pkg.codePath);
23765                final File probeOat = new File(probe, "oat");
23766                if (!probe.isDirectory() || !probeOat.isDirectory()) {
23767                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23768                            "Move only supported for modern cluster style installs");
23769                }
23770            }
23771
23772            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
23773                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23774                        "Package already moved to " + volumeUuid);
23775            }
23776            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
23777                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
23778                        "Device admin cannot be moved");
23779            }
23780
23781            if (mFrozenPackages.contains(packageName)) {
23782                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
23783                        "Failed to move already frozen package");
23784            }
23785
23786            codeFile = new File(pkg.codePath);
23787            installerPackageName = ps.installerPackageName;
23788            packageAbiOverride = ps.cpuAbiOverrideString;
23789            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
23790            seinfo = pkg.applicationInfo.seInfo;
23791            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
23792            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
23793            freezer = freezePackage(packageName, "movePackageInternal");
23794            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
23795        }
23796
23797        final Bundle extras = new Bundle();
23798        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
23799        extras.putString(Intent.EXTRA_TITLE, label);
23800        mMoveCallbacks.notifyCreated(moveId, extras);
23801
23802        int installFlags;
23803        final boolean moveCompleteApp;
23804        final File measurePath;
23805
23806        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
23807            installFlags = INSTALL_INTERNAL;
23808            moveCompleteApp = !currentAsec;
23809            measurePath = Environment.getDataAppDirectory(volumeUuid);
23810        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
23811            installFlags = INSTALL_EXTERNAL;
23812            moveCompleteApp = false;
23813            measurePath = storage.getPrimaryPhysicalVolume().getPath();
23814        } else {
23815            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
23816            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
23817                    || !volume.isMountedWritable()) {
23818                freezer.close();
23819                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23820                        "Move location not mounted private volume");
23821            }
23822
23823            Preconditions.checkState(!currentAsec);
23824
23825            installFlags = INSTALL_INTERNAL;
23826            moveCompleteApp = true;
23827            measurePath = Environment.getDataAppDirectory(volumeUuid);
23828        }
23829
23830        // If we're moving app data around, we need all the users unlocked
23831        if (moveCompleteApp) {
23832            for (int userId : installedUserIds) {
23833                if (StorageManager.isFileEncryptedNativeOrEmulated()
23834                        && !StorageManager.isUserKeyUnlocked(userId)) {
23835                    throw new PackageManagerException(MOVE_FAILED_LOCKED_USER,
23836                            "User " + userId + " must be unlocked");
23837                }
23838            }
23839        }
23840
23841        final PackageStats stats = new PackageStats(null, -1);
23842        synchronized (mInstaller) {
23843            for (int userId : installedUserIds) {
23844                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
23845                    freezer.close();
23846                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23847                            "Failed to measure package size");
23848                }
23849            }
23850        }
23851
23852        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
23853                + stats.dataSize);
23854
23855        final long startFreeBytes = measurePath.getUsableSpace();
23856        final long sizeBytes;
23857        if (moveCompleteApp) {
23858            sizeBytes = stats.codeSize + stats.dataSize;
23859        } else {
23860            sizeBytes = stats.codeSize;
23861        }
23862
23863        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
23864            freezer.close();
23865            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23866                    "Not enough free space to move");
23867        }
23868
23869        mMoveCallbacks.notifyStatusChanged(moveId, 10);
23870
23871        final CountDownLatch installedLatch = new CountDownLatch(1);
23872        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
23873            @Override
23874            public void onUserActionRequired(Intent intent) throws RemoteException {
23875                throw new IllegalStateException();
23876            }
23877
23878            @Override
23879            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
23880                    Bundle extras) throws RemoteException {
23881                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
23882                        + PackageManager.installStatusToString(returnCode, msg));
23883
23884                installedLatch.countDown();
23885                freezer.close();
23886
23887                final int status = PackageManager.installStatusToPublicStatus(returnCode);
23888                switch (status) {
23889                    case PackageInstaller.STATUS_SUCCESS:
23890                        mMoveCallbacks.notifyStatusChanged(moveId,
23891                                PackageManager.MOVE_SUCCEEDED);
23892                        break;
23893                    case PackageInstaller.STATUS_FAILURE_STORAGE:
23894                        mMoveCallbacks.notifyStatusChanged(moveId,
23895                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
23896                        break;
23897                    default:
23898                        mMoveCallbacks.notifyStatusChanged(moveId,
23899                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
23900                        break;
23901                }
23902            }
23903        };
23904
23905        final MoveInfo move;
23906        if (moveCompleteApp) {
23907            // Kick off a thread to report progress estimates
23908            new Thread() {
23909                @Override
23910                public void run() {
23911                    while (true) {
23912                        try {
23913                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
23914                                break;
23915                            }
23916                        } catch (InterruptedException ignored) {
23917                        }
23918
23919                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
23920                        final int progress = 10 + (int) MathUtils.constrain(
23921                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
23922                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
23923                    }
23924                }
23925            }.start();
23926
23927            final String dataAppName = codeFile.getName();
23928            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
23929                    dataAppName, appId, seinfo, targetSdkVersion);
23930        } else {
23931            move = null;
23932        }
23933
23934        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
23935
23936        final Message msg = mHandler.obtainMessage(INIT_COPY);
23937        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
23938        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
23939                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
23940                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
23941                PackageManager.INSTALL_REASON_UNKNOWN);
23942        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
23943        msg.obj = params;
23944
23945        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
23946                System.identityHashCode(msg.obj));
23947        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
23948                System.identityHashCode(msg.obj));
23949
23950        mHandler.sendMessage(msg);
23951    }
23952
23953    @Override
23954    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
23955        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
23956
23957        final int realMoveId = mNextMoveId.getAndIncrement();
23958        final Bundle extras = new Bundle();
23959        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
23960        mMoveCallbacks.notifyCreated(realMoveId, extras);
23961
23962        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
23963            @Override
23964            public void onCreated(int moveId, Bundle extras) {
23965                // Ignored
23966            }
23967
23968            @Override
23969            public void onStatusChanged(int moveId, int status, long estMillis) {
23970                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
23971            }
23972        };
23973
23974        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23975        storage.setPrimaryStorageUuid(volumeUuid, callback);
23976        return realMoveId;
23977    }
23978
23979    @Override
23980    public int getMoveStatus(int moveId) {
23981        mContext.enforceCallingOrSelfPermission(
23982                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23983        return mMoveCallbacks.mLastStatus.get(moveId);
23984    }
23985
23986    @Override
23987    public void registerMoveCallback(IPackageMoveObserver callback) {
23988        mContext.enforceCallingOrSelfPermission(
23989                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23990        mMoveCallbacks.register(callback);
23991    }
23992
23993    @Override
23994    public void unregisterMoveCallback(IPackageMoveObserver callback) {
23995        mContext.enforceCallingOrSelfPermission(
23996                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23997        mMoveCallbacks.unregister(callback);
23998    }
23999
24000    @Override
24001    public boolean setInstallLocation(int loc) {
24002        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
24003                null);
24004        if (getInstallLocation() == loc) {
24005            return true;
24006        }
24007        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
24008                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
24009            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
24010                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
24011            return true;
24012        }
24013        return false;
24014   }
24015
24016    @Override
24017    public int getInstallLocation() {
24018        // allow instant app access
24019        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
24020                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
24021                PackageHelper.APP_INSTALL_AUTO);
24022    }
24023
24024    /** Called by UserManagerService */
24025    void cleanUpUser(UserManagerService userManager, int userHandle) {
24026        synchronized (mPackages) {
24027            mDirtyUsers.remove(userHandle);
24028            mUserNeedsBadging.delete(userHandle);
24029            mSettings.removeUserLPw(userHandle);
24030            mPendingBroadcasts.remove(userHandle);
24031            mInstantAppRegistry.onUserRemovedLPw(userHandle);
24032            removeUnusedPackagesLPw(userManager, userHandle);
24033        }
24034    }
24035
24036    /**
24037     * We're removing userHandle and would like to remove any downloaded packages
24038     * that are no longer in use by any other user.
24039     * @param userHandle the user being removed
24040     */
24041    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
24042        final boolean DEBUG_CLEAN_APKS = false;
24043        int [] users = userManager.getUserIds();
24044        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
24045        while (psit.hasNext()) {
24046            PackageSetting ps = psit.next();
24047            if (ps.pkg == null) {
24048                continue;
24049            }
24050            final String packageName = ps.pkg.packageName;
24051            // Skip over if system app
24052            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
24053                continue;
24054            }
24055            if (DEBUG_CLEAN_APKS) {
24056                Slog.i(TAG, "Checking package " + packageName);
24057            }
24058            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
24059            if (keep) {
24060                if (DEBUG_CLEAN_APKS) {
24061                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
24062                }
24063            } else {
24064                for (int i = 0; i < users.length; i++) {
24065                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
24066                        keep = true;
24067                        if (DEBUG_CLEAN_APKS) {
24068                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
24069                                    + users[i]);
24070                        }
24071                        break;
24072                    }
24073                }
24074            }
24075            if (!keep) {
24076                if (DEBUG_CLEAN_APKS) {
24077                    Slog.i(TAG, "  Removing package " + packageName);
24078                }
24079                mHandler.post(new Runnable() {
24080                    public void run() {
24081                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
24082                                userHandle, 0);
24083                    } //end run
24084                });
24085            }
24086        }
24087    }
24088
24089    /** Called by UserManagerService */
24090    void createNewUser(int userId, String[] disallowedPackages) {
24091        synchronized (mInstallLock) {
24092            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
24093        }
24094        synchronized (mPackages) {
24095            scheduleWritePackageRestrictionsLocked(userId);
24096            scheduleWritePackageListLocked(userId);
24097            applyFactoryDefaultBrowserLPw(userId);
24098            primeDomainVerificationsLPw(userId);
24099        }
24100    }
24101
24102    void onNewUserCreated(final int userId) {
24103        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
24104        // If permission review for legacy apps is required, we represent
24105        // dagerous permissions for such apps as always granted runtime
24106        // permissions to keep per user flag state whether review is needed.
24107        // Hence, if a new user is added we have to propagate dangerous
24108        // permission grants for these legacy apps.
24109        if (mPermissionReviewRequired) {
24110            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
24111                    | UPDATE_PERMISSIONS_REPLACE_ALL);
24112        }
24113    }
24114
24115    @Override
24116    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
24117        mContext.enforceCallingOrSelfPermission(
24118                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
24119                "Only package verification agents can read the verifier device identity");
24120
24121        synchronized (mPackages) {
24122            return mSettings.getVerifierDeviceIdentityLPw();
24123        }
24124    }
24125
24126    @Override
24127    public void setPermissionEnforced(String permission, boolean enforced) {
24128        // TODO: Now that we no longer change GID for storage, this should to away.
24129        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
24130                "setPermissionEnforced");
24131        if (READ_EXTERNAL_STORAGE.equals(permission)) {
24132            synchronized (mPackages) {
24133                if (mSettings.mReadExternalStorageEnforced == null
24134                        || mSettings.mReadExternalStorageEnforced != enforced) {
24135                    mSettings.mReadExternalStorageEnforced = enforced;
24136                    mSettings.writeLPr();
24137                }
24138            }
24139            // kill any non-foreground processes so we restart them and
24140            // grant/revoke the GID.
24141            final IActivityManager am = ActivityManager.getService();
24142            if (am != null) {
24143                final long token = Binder.clearCallingIdentity();
24144                try {
24145                    am.killProcessesBelowForeground("setPermissionEnforcement");
24146                } catch (RemoteException e) {
24147                } finally {
24148                    Binder.restoreCallingIdentity(token);
24149                }
24150            }
24151        } else {
24152            throw new IllegalArgumentException("No selective enforcement for " + permission);
24153        }
24154    }
24155
24156    @Override
24157    @Deprecated
24158    public boolean isPermissionEnforced(String permission) {
24159        // allow instant applications
24160        return true;
24161    }
24162
24163    @Override
24164    public boolean isStorageLow() {
24165        // allow instant applications
24166        final long token = Binder.clearCallingIdentity();
24167        try {
24168            final DeviceStorageMonitorInternal
24169                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
24170            if (dsm != null) {
24171                return dsm.isMemoryLow();
24172            } else {
24173                return false;
24174            }
24175        } finally {
24176            Binder.restoreCallingIdentity(token);
24177        }
24178    }
24179
24180    @Override
24181    public IPackageInstaller getPackageInstaller() {
24182        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24183            return null;
24184        }
24185        return mInstallerService;
24186    }
24187
24188    private boolean userNeedsBadging(int userId) {
24189        int index = mUserNeedsBadging.indexOfKey(userId);
24190        if (index < 0) {
24191            final UserInfo userInfo;
24192            final long token = Binder.clearCallingIdentity();
24193            try {
24194                userInfo = sUserManager.getUserInfo(userId);
24195            } finally {
24196                Binder.restoreCallingIdentity(token);
24197            }
24198            final boolean b;
24199            if (userInfo != null && userInfo.isManagedProfile()) {
24200                b = true;
24201            } else {
24202                b = false;
24203            }
24204            mUserNeedsBadging.put(userId, b);
24205            return b;
24206        }
24207        return mUserNeedsBadging.valueAt(index);
24208    }
24209
24210    @Override
24211    public KeySet getKeySetByAlias(String packageName, String alias) {
24212        if (packageName == null || alias == null) {
24213            return null;
24214        }
24215        synchronized(mPackages) {
24216            final PackageParser.Package pkg = mPackages.get(packageName);
24217            if (pkg == null) {
24218                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24219                throw new IllegalArgumentException("Unknown package: " + packageName);
24220            }
24221            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24222            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
24223                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
24224                throw new IllegalArgumentException("Unknown package: " + packageName);
24225            }
24226            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24227            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
24228        }
24229    }
24230
24231    @Override
24232    public KeySet getSigningKeySet(String packageName) {
24233        if (packageName == null) {
24234            return null;
24235        }
24236        synchronized(mPackages) {
24237            final int callingUid = Binder.getCallingUid();
24238            final int callingUserId = UserHandle.getUserId(callingUid);
24239            final PackageParser.Package pkg = mPackages.get(packageName);
24240            if (pkg == null) {
24241                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24242                throw new IllegalArgumentException("Unknown package: " + packageName);
24243            }
24244            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24245            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
24246                // filter and pretend the package doesn't exist
24247                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
24248                        + ", uid:" + callingUid);
24249                throw new IllegalArgumentException("Unknown package: " + packageName);
24250            }
24251            if (pkg.applicationInfo.uid != callingUid
24252                    && Process.SYSTEM_UID != callingUid) {
24253                throw new SecurityException("May not access signing KeySet of other apps.");
24254            }
24255            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24256            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
24257        }
24258    }
24259
24260    @Override
24261    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
24262        final int callingUid = Binder.getCallingUid();
24263        if (getInstantAppPackageName(callingUid) != null) {
24264            return false;
24265        }
24266        if (packageName == null || ks == null) {
24267            return false;
24268        }
24269        synchronized(mPackages) {
24270            final PackageParser.Package pkg = mPackages.get(packageName);
24271            if (pkg == null
24272                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24273                            UserHandle.getUserId(callingUid))) {
24274                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24275                throw new IllegalArgumentException("Unknown package: " + packageName);
24276            }
24277            IBinder ksh = ks.getToken();
24278            if (ksh instanceof KeySetHandle) {
24279                KeySetManagerService ksms = mSettings.mKeySetManagerService;
24280                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
24281            }
24282            return false;
24283        }
24284    }
24285
24286    @Override
24287    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
24288        final int callingUid = Binder.getCallingUid();
24289        if (getInstantAppPackageName(callingUid) != null) {
24290            return false;
24291        }
24292        if (packageName == null || ks == null) {
24293            return false;
24294        }
24295        synchronized(mPackages) {
24296            final PackageParser.Package pkg = mPackages.get(packageName);
24297            if (pkg == null
24298                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24299                            UserHandle.getUserId(callingUid))) {
24300                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24301                throw new IllegalArgumentException("Unknown package: " + packageName);
24302            }
24303            IBinder ksh = ks.getToken();
24304            if (ksh instanceof KeySetHandle) {
24305                KeySetManagerService ksms = mSettings.mKeySetManagerService;
24306                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
24307            }
24308            return false;
24309        }
24310    }
24311
24312    private void deletePackageIfUnusedLPr(final String packageName) {
24313        PackageSetting ps = mSettings.mPackages.get(packageName);
24314        if (ps == null) {
24315            return;
24316        }
24317        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
24318            // TODO Implement atomic delete if package is unused
24319            // It is currently possible that the package will be deleted even if it is installed
24320            // after this method returns.
24321            mHandler.post(new Runnable() {
24322                public void run() {
24323                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
24324                            0, PackageManager.DELETE_ALL_USERS);
24325                }
24326            });
24327        }
24328    }
24329
24330    /**
24331     * Check and throw if the given before/after packages would be considered a
24332     * downgrade.
24333     */
24334    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
24335            throws PackageManagerException {
24336        if (after.versionCode < before.mVersionCode) {
24337            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24338                    "Update version code " + after.versionCode + " is older than current "
24339                    + before.mVersionCode);
24340        } else if (after.versionCode == before.mVersionCode) {
24341            if (after.baseRevisionCode < before.baseRevisionCode) {
24342                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24343                        "Update base revision code " + after.baseRevisionCode
24344                        + " is older than current " + before.baseRevisionCode);
24345            }
24346
24347            if (!ArrayUtils.isEmpty(after.splitNames)) {
24348                for (int i = 0; i < after.splitNames.length; i++) {
24349                    final String splitName = after.splitNames[i];
24350                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
24351                    if (j != -1) {
24352                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
24353                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24354                                    "Update split " + splitName + " revision code "
24355                                    + after.splitRevisionCodes[i] + " is older than current "
24356                                    + before.splitRevisionCodes[j]);
24357                        }
24358                    }
24359                }
24360            }
24361        }
24362    }
24363
24364    private static class MoveCallbacks extends Handler {
24365        private static final int MSG_CREATED = 1;
24366        private static final int MSG_STATUS_CHANGED = 2;
24367
24368        private final RemoteCallbackList<IPackageMoveObserver>
24369                mCallbacks = new RemoteCallbackList<>();
24370
24371        private final SparseIntArray mLastStatus = new SparseIntArray();
24372
24373        public MoveCallbacks(Looper looper) {
24374            super(looper);
24375        }
24376
24377        public void register(IPackageMoveObserver callback) {
24378            mCallbacks.register(callback);
24379        }
24380
24381        public void unregister(IPackageMoveObserver callback) {
24382            mCallbacks.unregister(callback);
24383        }
24384
24385        @Override
24386        public void handleMessage(Message msg) {
24387            final SomeArgs args = (SomeArgs) msg.obj;
24388            final int n = mCallbacks.beginBroadcast();
24389            for (int i = 0; i < n; i++) {
24390                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
24391                try {
24392                    invokeCallback(callback, msg.what, args);
24393                } catch (RemoteException ignored) {
24394                }
24395            }
24396            mCallbacks.finishBroadcast();
24397            args.recycle();
24398        }
24399
24400        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
24401                throws RemoteException {
24402            switch (what) {
24403                case MSG_CREATED: {
24404                    callback.onCreated(args.argi1, (Bundle) args.arg2);
24405                    break;
24406                }
24407                case MSG_STATUS_CHANGED: {
24408                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
24409                    break;
24410                }
24411            }
24412        }
24413
24414        private void notifyCreated(int moveId, Bundle extras) {
24415            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
24416
24417            final SomeArgs args = SomeArgs.obtain();
24418            args.argi1 = moveId;
24419            args.arg2 = extras;
24420            obtainMessage(MSG_CREATED, args).sendToTarget();
24421        }
24422
24423        private void notifyStatusChanged(int moveId, int status) {
24424            notifyStatusChanged(moveId, status, -1);
24425        }
24426
24427        private void notifyStatusChanged(int moveId, int status, long estMillis) {
24428            Slog.v(TAG, "Move " + moveId + " status " + status);
24429
24430            final SomeArgs args = SomeArgs.obtain();
24431            args.argi1 = moveId;
24432            args.argi2 = status;
24433            args.arg3 = estMillis;
24434            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
24435
24436            synchronized (mLastStatus) {
24437                mLastStatus.put(moveId, status);
24438            }
24439        }
24440    }
24441
24442    private final static class OnPermissionChangeListeners extends Handler {
24443        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
24444
24445        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
24446                new RemoteCallbackList<>();
24447
24448        public OnPermissionChangeListeners(Looper looper) {
24449            super(looper);
24450        }
24451
24452        @Override
24453        public void handleMessage(Message msg) {
24454            switch (msg.what) {
24455                case MSG_ON_PERMISSIONS_CHANGED: {
24456                    final int uid = msg.arg1;
24457                    handleOnPermissionsChanged(uid);
24458                } break;
24459            }
24460        }
24461
24462        public void addListenerLocked(IOnPermissionsChangeListener listener) {
24463            mPermissionListeners.register(listener);
24464
24465        }
24466
24467        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
24468            mPermissionListeners.unregister(listener);
24469        }
24470
24471        public void onPermissionsChanged(int uid) {
24472            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
24473                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
24474            }
24475        }
24476
24477        private void handleOnPermissionsChanged(int uid) {
24478            final int count = mPermissionListeners.beginBroadcast();
24479            try {
24480                for (int i = 0; i < count; i++) {
24481                    IOnPermissionsChangeListener callback = mPermissionListeners
24482                            .getBroadcastItem(i);
24483                    try {
24484                        callback.onPermissionsChanged(uid);
24485                    } catch (RemoteException e) {
24486                        Log.e(TAG, "Permission listener is dead", e);
24487                    }
24488                }
24489            } finally {
24490                mPermissionListeners.finishBroadcast();
24491            }
24492        }
24493    }
24494
24495    private class PackageManagerInternalImpl extends PackageManagerInternal {
24496        @Override
24497        public void setLocationPackagesProvider(PackagesProvider provider) {
24498            synchronized (mPackages) {
24499                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
24500            }
24501        }
24502
24503        @Override
24504        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
24505            synchronized (mPackages) {
24506                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
24507            }
24508        }
24509
24510        @Override
24511        public void setSmsAppPackagesProvider(PackagesProvider provider) {
24512            synchronized (mPackages) {
24513                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
24514            }
24515        }
24516
24517        @Override
24518        public void setDialerAppPackagesProvider(PackagesProvider provider) {
24519            synchronized (mPackages) {
24520                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
24521            }
24522        }
24523
24524        @Override
24525        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
24526            synchronized (mPackages) {
24527                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
24528            }
24529        }
24530
24531        @Override
24532        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
24533            synchronized (mPackages) {
24534                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
24535            }
24536        }
24537
24538        @Override
24539        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
24540            synchronized (mPackages) {
24541                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
24542                        packageName, userId);
24543            }
24544        }
24545
24546        @Override
24547        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
24548            synchronized (mPackages) {
24549                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
24550                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
24551                        packageName, userId);
24552            }
24553        }
24554
24555        @Override
24556        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
24557            synchronized (mPackages) {
24558                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
24559                        packageName, userId);
24560            }
24561        }
24562
24563        @Override
24564        public void setKeepUninstalledPackages(final List<String> packageList) {
24565            Preconditions.checkNotNull(packageList);
24566            List<String> removedFromList = null;
24567            synchronized (mPackages) {
24568                if (mKeepUninstalledPackages != null) {
24569                    final int packagesCount = mKeepUninstalledPackages.size();
24570                    for (int i = 0; i < packagesCount; i++) {
24571                        String oldPackage = mKeepUninstalledPackages.get(i);
24572                        if (packageList != null && packageList.contains(oldPackage)) {
24573                            continue;
24574                        }
24575                        if (removedFromList == null) {
24576                            removedFromList = new ArrayList<>();
24577                        }
24578                        removedFromList.add(oldPackage);
24579                    }
24580                }
24581                mKeepUninstalledPackages = new ArrayList<>(packageList);
24582                if (removedFromList != null) {
24583                    final int removedCount = removedFromList.size();
24584                    for (int i = 0; i < removedCount; i++) {
24585                        deletePackageIfUnusedLPr(removedFromList.get(i));
24586                    }
24587                }
24588            }
24589        }
24590
24591        @Override
24592        public boolean isPermissionsReviewRequired(String packageName, int userId) {
24593            synchronized (mPackages) {
24594                // If we do not support permission review, done.
24595                if (!mPermissionReviewRequired) {
24596                    return false;
24597                }
24598
24599                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
24600                if (packageSetting == null) {
24601                    return false;
24602                }
24603
24604                // Permission review applies only to apps not supporting the new permission model.
24605                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
24606                    return false;
24607                }
24608
24609                // Legacy apps have the permission and get user consent on launch.
24610                PermissionsState permissionsState = packageSetting.getPermissionsState();
24611                return permissionsState.isPermissionReviewRequired(userId);
24612            }
24613        }
24614
24615        @Override
24616        public PackageInfo getPackageInfo(
24617                String packageName, int flags, int filterCallingUid, int userId) {
24618            return PackageManagerService.this
24619                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
24620                            flags, filterCallingUid, userId);
24621        }
24622
24623        @Override
24624        public ApplicationInfo getApplicationInfo(
24625                String packageName, int flags, int filterCallingUid, int userId) {
24626            return PackageManagerService.this
24627                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
24628        }
24629
24630        @Override
24631        public ActivityInfo getActivityInfo(
24632                ComponentName component, int flags, int filterCallingUid, int userId) {
24633            return PackageManagerService.this
24634                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
24635        }
24636
24637        @Override
24638        public List<ResolveInfo> queryIntentActivities(
24639                Intent intent, int flags, int filterCallingUid, int userId) {
24640            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
24641            return PackageManagerService.this
24642                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
24643                            userId, false /*resolveForStart*/);
24644        }
24645
24646        @Override
24647        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
24648                int userId) {
24649            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
24650        }
24651
24652        @Override
24653        public void setDeviceAndProfileOwnerPackages(
24654                int deviceOwnerUserId, String deviceOwnerPackage,
24655                SparseArray<String> profileOwnerPackages) {
24656            mProtectedPackages.setDeviceAndProfileOwnerPackages(
24657                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
24658        }
24659
24660        @Override
24661        public boolean isPackageDataProtected(int userId, String packageName) {
24662            return mProtectedPackages.isPackageDataProtected(userId, packageName);
24663        }
24664
24665        @Override
24666        public boolean isPackageEphemeral(int userId, String packageName) {
24667            synchronized (mPackages) {
24668                final PackageSetting ps = mSettings.mPackages.get(packageName);
24669                return ps != null ? ps.getInstantApp(userId) : false;
24670            }
24671        }
24672
24673        @Override
24674        public boolean wasPackageEverLaunched(String packageName, int userId) {
24675            synchronized (mPackages) {
24676                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
24677            }
24678        }
24679
24680        @Override
24681        public void grantRuntimePermission(String packageName, String name, int userId,
24682                boolean overridePolicy) {
24683            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
24684                    overridePolicy);
24685        }
24686
24687        @Override
24688        public void revokeRuntimePermission(String packageName, String name, int userId,
24689                boolean overridePolicy) {
24690            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
24691                    overridePolicy);
24692        }
24693
24694        @Override
24695        public String getNameForUid(int uid) {
24696            return PackageManagerService.this.getNameForUid(uid);
24697        }
24698
24699        @Override
24700        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
24701                Intent origIntent, String resolvedType, String callingPackage,
24702                Bundle verificationBundle, int userId) {
24703            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
24704                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
24705                    userId);
24706        }
24707
24708        @Override
24709        public void grantEphemeralAccess(int userId, Intent intent,
24710                int targetAppId, int ephemeralAppId) {
24711            synchronized (mPackages) {
24712                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
24713                        targetAppId, ephemeralAppId);
24714            }
24715        }
24716
24717        @Override
24718        public boolean isInstantAppInstallerComponent(ComponentName component) {
24719            synchronized (mPackages) {
24720                return mInstantAppInstallerActivity != null
24721                        && mInstantAppInstallerActivity.getComponentName().equals(component);
24722            }
24723        }
24724
24725        @Override
24726        public void pruneInstantApps() {
24727            mInstantAppRegistry.pruneInstantApps();
24728        }
24729
24730        @Override
24731        public String getSetupWizardPackageName() {
24732            return mSetupWizardPackage;
24733        }
24734
24735        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
24736            if (policy != null) {
24737                mExternalSourcesPolicy = policy;
24738            }
24739        }
24740
24741        @Override
24742        public boolean isPackagePersistent(String packageName) {
24743            synchronized (mPackages) {
24744                PackageParser.Package pkg = mPackages.get(packageName);
24745                return pkg != null
24746                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
24747                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
24748                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
24749                        : false;
24750            }
24751        }
24752
24753        @Override
24754        public List<PackageInfo> getOverlayPackages(int userId) {
24755            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
24756            synchronized (mPackages) {
24757                for (PackageParser.Package p : mPackages.values()) {
24758                    if (p.mOverlayTarget != null) {
24759                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
24760                        if (pkg != null) {
24761                            overlayPackages.add(pkg);
24762                        }
24763                    }
24764                }
24765            }
24766            return overlayPackages;
24767        }
24768
24769        @Override
24770        public List<String> getTargetPackageNames(int userId) {
24771            List<String> targetPackages = new ArrayList<>();
24772            synchronized (mPackages) {
24773                for (PackageParser.Package p : mPackages.values()) {
24774                    if (p.mOverlayTarget == null) {
24775                        targetPackages.add(p.packageName);
24776                    }
24777                }
24778            }
24779            return targetPackages;
24780        }
24781
24782        @Override
24783        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
24784                @Nullable List<String> overlayPackageNames) {
24785            synchronized (mPackages) {
24786                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
24787                    Slog.e(TAG, "failed to find package " + targetPackageName);
24788                    return false;
24789                }
24790                ArrayList<String> overlayPaths = null;
24791                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
24792                    final int N = overlayPackageNames.size();
24793                    overlayPaths = new ArrayList<>(N);
24794                    for (int i = 0; i < N; i++) {
24795                        final String packageName = overlayPackageNames.get(i);
24796                        final PackageParser.Package pkg = mPackages.get(packageName);
24797                        if (pkg == null) {
24798                            Slog.e(TAG, "failed to find package " + packageName);
24799                            return false;
24800                        }
24801                        overlayPaths.add(pkg.baseCodePath);
24802                    }
24803                }
24804
24805                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
24806                ps.setOverlayPaths(overlayPaths, userId);
24807                return true;
24808            }
24809        }
24810
24811        @Override
24812        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
24813                int flags, int userId) {
24814            return resolveIntentInternal(
24815                    intent, resolvedType, flags, userId, true /*resolveForStart*/);
24816        }
24817
24818        @Override
24819        public ResolveInfo resolveService(Intent intent, String resolvedType,
24820                int flags, int userId, int callingUid) {
24821            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
24822        }
24823
24824        @Override
24825        public void addIsolatedUid(int isolatedUid, int ownerUid) {
24826            synchronized (mPackages) {
24827                mIsolatedOwners.put(isolatedUid, ownerUid);
24828            }
24829        }
24830
24831        @Override
24832        public void removeIsolatedUid(int isolatedUid) {
24833            synchronized (mPackages) {
24834                mIsolatedOwners.delete(isolatedUid);
24835            }
24836        }
24837
24838        @Override
24839        public int getUidTargetSdkVersion(int uid) {
24840            synchronized (mPackages) {
24841                return getUidTargetSdkVersionLockedLPr(uid);
24842            }
24843        }
24844
24845        @Override
24846        public boolean canAccessInstantApps(int callingUid, int userId) {
24847            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
24848        }
24849    }
24850
24851    @Override
24852    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
24853        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
24854        synchronized (mPackages) {
24855            final long identity = Binder.clearCallingIdentity();
24856            try {
24857                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
24858                        packageNames, userId);
24859            } finally {
24860                Binder.restoreCallingIdentity(identity);
24861            }
24862        }
24863    }
24864
24865    @Override
24866    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
24867        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
24868        synchronized (mPackages) {
24869            final long identity = Binder.clearCallingIdentity();
24870            try {
24871                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr(
24872                        packageNames, userId);
24873            } finally {
24874                Binder.restoreCallingIdentity(identity);
24875            }
24876        }
24877    }
24878
24879    private static void enforceSystemOrPhoneCaller(String tag) {
24880        int callingUid = Binder.getCallingUid();
24881        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
24882            throw new SecurityException(
24883                    "Cannot call " + tag + " from UID " + callingUid);
24884        }
24885    }
24886
24887    boolean isHistoricalPackageUsageAvailable() {
24888        return mPackageUsage.isHistoricalPackageUsageAvailable();
24889    }
24890
24891    /**
24892     * Return a <b>copy</b> of the collection of packages known to the package manager.
24893     * @return A copy of the values of mPackages.
24894     */
24895    Collection<PackageParser.Package> getPackages() {
24896        synchronized (mPackages) {
24897            return new ArrayList<>(mPackages.values());
24898        }
24899    }
24900
24901    /**
24902     * Logs process start information (including base APK hash) to the security log.
24903     * @hide
24904     */
24905    @Override
24906    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
24907            String apkFile, int pid) {
24908        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24909            return;
24910        }
24911        if (!SecurityLog.isLoggingEnabled()) {
24912            return;
24913        }
24914        Bundle data = new Bundle();
24915        data.putLong("startTimestamp", System.currentTimeMillis());
24916        data.putString("processName", processName);
24917        data.putInt("uid", uid);
24918        data.putString("seinfo", seinfo);
24919        data.putString("apkFile", apkFile);
24920        data.putInt("pid", pid);
24921        Message msg = mProcessLoggingHandler.obtainMessage(
24922                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
24923        msg.setData(data);
24924        mProcessLoggingHandler.sendMessage(msg);
24925    }
24926
24927    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
24928        return mCompilerStats.getPackageStats(pkgName);
24929    }
24930
24931    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
24932        return getOrCreateCompilerPackageStats(pkg.packageName);
24933    }
24934
24935    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
24936        return mCompilerStats.getOrCreatePackageStats(pkgName);
24937    }
24938
24939    public void deleteCompilerPackageStats(String pkgName) {
24940        mCompilerStats.deletePackageStats(pkgName);
24941    }
24942
24943    @Override
24944    public int getInstallReason(String packageName, int userId) {
24945        final int callingUid = Binder.getCallingUid();
24946        enforceCrossUserPermission(callingUid, userId,
24947                true /* requireFullPermission */, false /* checkShell */,
24948                "get install reason");
24949        synchronized (mPackages) {
24950            final PackageSetting ps = mSettings.mPackages.get(packageName);
24951            if (filterAppAccessLPr(ps, callingUid, userId)) {
24952                return PackageManager.INSTALL_REASON_UNKNOWN;
24953            }
24954            if (ps != null) {
24955                return ps.getInstallReason(userId);
24956            }
24957        }
24958        return PackageManager.INSTALL_REASON_UNKNOWN;
24959    }
24960
24961    @Override
24962    public boolean canRequestPackageInstalls(String packageName, int userId) {
24963        return canRequestPackageInstallsInternal(packageName, 0, userId,
24964                true /* throwIfPermNotDeclared*/);
24965    }
24966
24967    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
24968            boolean throwIfPermNotDeclared) {
24969        int callingUid = Binder.getCallingUid();
24970        int uid = getPackageUid(packageName, 0, userId);
24971        if (callingUid != uid && callingUid != Process.ROOT_UID
24972                && callingUid != Process.SYSTEM_UID) {
24973            throw new SecurityException(
24974                    "Caller uid " + callingUid + " does not own package " + packageName);
24975        }
24976        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
24977        if (info == null) {
24978            return false;
24979        }
24980        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
24981            return false;
24982        }
24983        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
24984        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
24985        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
24986            if (throwIfPermNotDeclared) {
24987                throw new SecurityException("Need to declare " + appOpPermission
24988                        + " to call this api");
24989            } else {
24990                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
24991                return false;
24992            }
24993        }
24994        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
24995            return false;
24996        }
24997        if (mExternalSourcesPolicy != null) {
24998            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
24999            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
25000                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
25001            }
25002        }
25003        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
25004    }
25005
25006    @Override
25007    public ComponentName getInstantAppResolverSettingsComponent() {
25008        return mInstantAppResolverSettingsComponent;
25009    }
25010
25011    @Override
25012    public ComponentName getInstantAppInstallerComponent() {
25013        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
25014            return null;
25015        }
25016        return mInstantAppInstallerActivity == null
25017                ? null : mInstantAppInstallerActivity.getComponentName();
25018    }
25019
25020    @Override
25021    public String getInstantAppAndroidId(String packageName, int userId) {
25022        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
25023                "getInstantAppAndroidId");
25024        enforceCrossUserPermission(Binder.getCallingUid(), userId,
25025                true /* requireFullPermission */, false /* checkShell */,
25026                "getInstantAppAndroidId");
25027        // Make sure the target is an Instant App.
25028        if (!isInstantApp(packageName, userId)) {
25029            return null;
25030        }
25031        synchronized (mPackages) {
25032            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
25033        }
25034    }
25035
25036    boolean canHaveOatDir(String packageName) {
25037        synchronized (mPackages) {
25038            PackageParser.Package p = mPackages.get(packageName);
25039            if (p == null) {
25040                return false;
25041            }
25042            return p.canHaveOatDir();
25043        }
25044    }
25045
25046    private String getOatDir(PackageParser.Package pkg) {
25047        if (!pkg.canHaveOatDir()) {
25048            return null;
25049        }
25050        File codePath = new File(pkg.codePath);
25051        if (codePath.isDirectory()) {
25052            return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath();
25053        }
25054        return null;
25055    }
25056
25057    void deleteOatArtifactsOfPackage(String packageName) {
25058        final String[] instructionSets;
25059        final List<String> codePaths;
25060        final String oatDir;
25061        final PackageParser.Package pkg;
25062        synchronized (mPackages) {
25063            pkg = mPackages.get(packageName);
25064        }
25065        instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
25066        codePaths = pkg.getAllCodePaths();
25067        oatDir = getOatDir(pkg);
25068
25069        for (String codePath : codePaths) {
25070            for (String isa : instructionSets) {
25071                try {
25072                    mInstaller.deleteOdex(codePath, isa, oatDir);
25073                } catch (InstallerException e) {
25074                    Log.e(TAG, "Failed deleting oat files for " + codePath, e);
25075                }
25076            }
25077        }
25078    }
25079
25080    Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) {
25081        Set<String> unusedPackages = new HashSet<>();
25082        long currentTimeInMillis = System.currentTimeMillis();
25083        synchronized (mPackages) {
25084            for (PackageParser.Package pkg : mPackages.values()) {
25085                PackageSetting ps =  mSettings.mPackages.get(pkg.packageName);
25086                if (ps == null) {
25087                    continue;
25088                }
25089                PackageDexUsage.PackageUseInfo packageUseInfo = getDexManager().getPackageUseInfo(
25090                        pkg.packageName);
25091                if (PackageManagerServiceUtils
25092                        .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis,
25093                                downgradeTimeThresholdMillis, packageUseInfo,
25094                                pkg.getLatestPackageUseTimeInMills(),
25095                                pkg.getLatestForegroundPackageUseTimeInMills())) {
25096                    unusedPackages.add(pkg.packageName);
25097                }
25098            }
25099        }
25100        return unusedPackages;
25101    }
25102}
25103
25104interface PackageSender {
25105    void sendPackageBroadcast(final String action, final String pkg,
25106        final Bundle extras, final int flags, final String targetPkg,
25107        final IIntentReceiver finishedReceiver, final int[] userIds);
25108    void sendPackageAddedForNewUsers(String packageName, boolean isSystem,
25109        int appId, int... userIds);
25110}
25111