PackageManagerService.java revision 3aeca17aa911394e7a4d2c1536b28423cb135b53
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.DELETE_PACKAGES;
20import static android.Manifest.permission.INSTALL_PACKAGES;
21import static android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS;
22import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
23import static android.Manifest.permission.REQUEST_DELETE_PACKAGES;
24import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
25import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
27import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
28import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
29import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
30import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
31import static android.content.pm.PackageManager.DELETE_KEEP_DATA;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
33import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
34import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
35import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
36import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
37import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
38import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
39import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
40import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
41import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
42import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
43import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
44import static android.content.pm.PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID;
45import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
46import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
47import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
48import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
49import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
50import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
51import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
52import static android.content.pm.PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE;
53import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
54import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
55import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
56import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
57import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
58import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
59import static android.content.pm.PackageManager.INSTALL_INTERNAL;
60import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
61import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
62import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
63import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
64import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
65import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
66import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
67import static android.content.pm.PackageManager.MATCH_ALL;
68import static android.content.pm.PackageManager.MATCH_ANY_USER;
69import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
70import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
71import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
72import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
73import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
74import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES;
75import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
76import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
77import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL;
78import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
79import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
80import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
81import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
82import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
83import static android.content.pm.PackageManager.PERMISSION_DENIED;
84import static android.content.pm.PackageManager.PERMISSION_GRANTED;
85import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
86import static android.content.pm.PackageParser.isApkFile;
87import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
88import static android.system.OsConstants.O_CREAT;
89import static android.system.OsConstants.O_RDWR;
90import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
91import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
92import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
93import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
94import static com.android.internal.util.ArrayUtils.appendInt;
95import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
96import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
97import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
98import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
99import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
100import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
101import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter;
102import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
103import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
104import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
105import static dalvik.system.DexFile.getNonProfileGuidedCompilerFilter;
106
107import android.Manifest;
108import android.annotation.IntDef;
109import android.annotation.NonNull;
110import android.annotation.Nullable;
111import android.app.ActivityManager;
112import android.app.AppOpsManager;
113import android.app.IActivityManager;
114import android.app.ResourcesManager;
115import android.app.admin.IDevicePolicyManager;
116import android.app.admin.SecurityLog;
117import android.app.backup.IBackupManager;
118import android.content.BroadcastReceiver;
119import android.content.ComponentName;
120import android.content.ContentResolver;
121import android.content.Context;
122import android.content.IIntentReceiver;
123import android.content.Intent;
124import android.content.IntentFilter;
125import android.content.IntentSender;
126import android.content.IntentSender.SendIntentException;
127import android.content.ServiceConnection;
128import android.content.pm.ActivityInfo;
129import android.content.pm.ApplicationInfo;
130import android.content.pm.AppsQueryHelper;
131import android.content.pm.AuxiliaryResolveInfo;
132import android.content.pm.ChangedPackages;
133import android.content.pm.FallbackCategoryProvider;
134import android.content.pm.FeatureInfo;
135import android.content.pm.IDexModuleRegisterCallback;
136import android.content.pm.IOnPermissionsChangeListener;
137import android.content.pm.IPackageDataObserver;
138import android.content.pm.IPackageDeleteObserver;
139import android.content.pm.IPackageDeleteObserver2;
140import android.content.pm.IPackageInstallObserver2;
141import android.content.pm.IPackageInstaller;
142import android.content.pm.IPackageManager;
143import android.content.pm.IPackageMoveObserver;
144import android.content.pm.IPackageStatsObserver;
145import android.content.pm.InstantAppInfo;
146import android.content.pm.InstantAppRequest;
147import android.content.pm.InstantAppResolveInfo;
148import android.content.pm.InstrumentationInfo;
149import android.content.pm.IntentFilterVerificationInfo;
150import android.content.pm.KeySet;
151import android.content.pm.PackageCleanItem;
152import android.content.pm.PackageInfo;
153import android.content.pm.PackageInfoLite;
154import android.content.pm.PackageInstaller;
155import android.content.pm.PackageManager;
156import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
157import android.content.pm.PackageManagerInternal;
158import android.content.pm.PackageParser;
159import android.content.pm.PackageParser.ActivityIntentInfo;
160import android.content.pm.PackageParser.PackageLite;
161import android.content.pm.PackageParser.PackageParserException;
162import android.content.pm.PackageStats;
163import android.content.pm.PackageUserState;
164import android.content.pm.ParceledListSlice;
165import android.content.pm.PermissionGroupInfo;
166import android.content.pm.PermissionInfo;
167import android.content.pm.ProviderInfo;
168import android.content.pm.ResolveInfo;
169import android.content.pm.ServiceInfo;
170import android.content.pm.SharedLibraryInfo;
171import android.content.pm.Signature;
172import android.content.pm.UserInfo;
173import android.content.pm.VerifierDeviceIdentity;
174import android.content.pm.VerifierInfo;
175import android.content.pm.VersionedPackage;
176import android.content.res.Resources;
177import android.database.ContentObserver;
178import android.graphics.Bitmap;
179import android.hardware.display.DisplayManager;
180import android.net.Uri;
181import android.os.Binder;
182import android.os.Build;
183import android.os.Bundle;
184import android.os.Debug;
185import android.os.Environment;
186import android.os.Environment.UserEnvironment;
187import android.os.FileUtils;
188import android.os.Handler;
189import android.os.IBinder;
190import android.os.Looper;
191import android.os.Message;
192import android.os.Parcel;
193import android.os.ParcelFileDescriptor;
194import android.os.PatternMatcher;
195import android.os.Process;
196import android.os.RemoteCallbackList;
197import android.os.RemoteException;
198import android.os.ResultReceiver;
199import android.os.SELinux;
200import android.os.ServiceManager;
201import android.os.ShellCallback;
202import android.os.SystemClock;
203import android.os.SystemProperties;
204import android.os.Trace;
205import android.os.UserHandle;
206import android.os.UserManager;
207import android.os.UserManagerInternal;
208import android.os.storage.IStorageManager;
209import android.os.storage.StorageEventListener;
210import android.os.storage.StorageManager;
211import android.os.storage.StorageManagerInternal;
212import android.os.storage.VolumeInfo;
213import android.os.storage.VolumeRecord;
214import android.provider.Settings.Global;
215import android.provider.Settings.Secure;
216import android.security.KeyStore;
217import android.security.SystemKeyStore;
218import android.service.pm.PackageServiceDumpProto;
219import android.system.ErrnoException;
220import android.system.Os;
221import android.text.TextUtils;
222import android.text.format.DateUtils;
223import android.util.ArrayMap;
224import android.util.ArraySet;
225import android.util.Base64;
226import android.util.BootTimingsTraceLog;
227import android.util.DisplayMetrics;
228import android.util.EventLog;
229import android.util.ExceptionUtils;
230import android.util.Log;
231import android.util.LogPrinter;
232import android.util.MathUtils;
233import android.util.PackageUtils;
234import android.util.Pair;
235import android.util.PrintStreamPrinter;
236import android.util.Slog;
237import android.util.SparseArray;
238import android.util.SparseBooleanArray;
239import android.util.SparseIntArray;
240import android.util.Xml;
241import android.util.jar.StrictJarFile;
242import android.util.proto.ProtoOutputStream;
243import android.view.Display;
244
245import com.android.internal.R;
246import com.android.internal.annotations.GuardedBy;
247import com.android.internal.app.IMediaContainerService;
248import com.android.internal.app.ResolverActivity;
249import com.android.internal.content.NativeLibraryHelper;
250import com.android.internal.content.PackageHelper;
251import com.android.internal.logging.MetricsLogger;
252import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
253import com.android.internal.os.IParcelFileDescriptorFactory;
254import com.android.internal.os.RoSystemProperties;
255import com.android.internal.os.SomeArgs;
256import com.android.internal.os.Zygote;
257import com.android.internal.telephony.CarrierAppUtils;
258import com.android.internal.util.ArrayUtils;
259import com.android.internal.util.ConcurrentUtils;
260import com.android.internal.util.DumpUtils;
261import com.android.internal.util.FastPrintWriter;
262import com.android.internal.util.FastXmlSerializer;
263import com.android.internal.util.IndentingPrintWriter;
264import com.android.internal.util.Preconditions;
265import com.android.internal.util.XmlUtils;
266import com.android.server.AttributeCache;
267import com.android.server.DeviceIdleController;
268import com.android.server.EventLogTags;
269import com.android.server.FgThread;
270import com.android.server.IntentResolver;
271import com.android.server.LocalServices;
272import com.android.server.LockGuard;
273import com.android.server.ServiceThread;
274import com.android.server.SystemConfig;
275import com.android.server.SystemServerInitThreadPool;
276import com.android.server.Watchdog;
277import com.android.server.net.NetworkPolicyManagerInternal;
278import com.android.server.pm.Installer.InstallerException;
279import com.android.server.pm.PermissionsState.PermissionState;
280import com.android.server.pm.Settings.DatabaseVersion;
281import com.android.server.pm.Settings.VersionInfo;
282import com.android.server.pm.dex.DexManager;
283import com.android.server.pm.dex.PackageDexUsage;
284import com.android.server.storage.DeviceStorageMonitorInternal;
285
286import dalvik.system.CloseGuard;
287import dalvik.system.DexFile;
288import dalvik.system.VMRuntime;
289
290import libcore.io.IoUtils;
291import libcore.util.EmptyArray;
292
293import org.xmlpull.v1.XmlPullParser;
294import org.xmlpull.v1.XmlPullParserException;
295import org.xmlpull.v1.XmlSerializer;
296
297import java.io.BufferedOutputStream;
298import java.io.BufferedReader;
299import java.io.ByteArrayInputStream;
300import java.io.ByteArrayOutputStream;
301import java.io.File;
302import java.io.FileDescriptor;
303import java.io.FileInputStream;
304import java.io.FileOutputStream;
305import java.io.FileReader;
306import java.io.FilenameFilter;
307import java.io.IOException;
308import java.io.PrintWriter;
309import java.lang.annotation.Retention;
310import java.lang.annotation.RetentionPolicy;
311import java.nio.charset.StandardCharsets;
312import java.security.DigestInputStream;
313import java.security.MessageDigest;
314import java.security.NoSuchAlgorithmException;
315import java.security.PublicKey;
316import java.security.SecureRandom;
317import java.security.cert.Certificate;
318import java.security.cert.CertificateEncodingException;
319import java.security.cert.CertificateException;
320import java.text.SimpleDateFormat;
321import java.util.ArrayList;
322import java.util.Arrays;
323import java.util.Collection;
324import java.util.Collections;
325import java.util.Comparator;
326import java.util.Date;
327import java.util.HashMap;
328import java.util.HashSet;
329import java.util.Iterator;
330import java.util.LinkedHashSet;
331import java.util.List;
332import java.util.Map;
333import java.util.Objects;
334import java.util.Set;
335import java.util.concurrent.CountDownLatch;
336import java.util.concurrent.Future;
337import java.util.concurrent.TimeUnit;
338import java.util.concurrent.atomic.AtomicBoolean;
339import java.util.concurrent.atomic.AtomicInteger;
340
341/**
342 * Keep track of all those APKs everywhere.
343 * <p>
344 * Internally there are two important locks:
345 * <ul>
346 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
347 * and other related state. It is a fine-grained lock that should only be held
348 * momentarily, as it's one of the most contended locks in the system.
349 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
350 * operations typically involve heavy lifting of application data on disk. Since
351 * {@code installd} is single-threaded, and it's operations can often be slow,
352 * this lock should never be acquired while already holding {@link #mPackages}.
353 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
354 * holding {@link #mInstallLock}.
355 * </ul>
356 * Many internal methods rely on the caller to hold the appropriate locks, and
357 * this contract is expressed through method name suffixes:
358 * <ul>
359 * <li>fooLI(): the caller must hold {@link #mInstallLock}
360 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
361 * being modified must be frozen
362 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
363 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
364 * </ul>
365 * <p>
366 * Because this class is very central to the platform's security; please run all
367 * CTS and unit tests whenever making modifications:
368 *
369 * <pre>
370 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
371 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
372 * </pre>
373 */
374public class PackageManagerService extends IPackageManager.Stub
375        implements PackageSender {
376    static final String TAG = "PackageManager";
377    static final boolean DEBUG_SETTINGS = false;
378    static final boolean DEBUG_PREFERRED = false;
379    static final boolean DEBUG_UPGRADE = false;
380    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
381    private static final boolean DEBUG_BACKUP = false;
382    private static final boolean DEBUG_INSTALL = false;
383    private static final boolean DEBUG_REMOVE = false;
384    private static final boolean DEBUG_BROADCASTS = false;
385    private static final boolean DEBUG_SHOW_INFO = false;
386    private static final boolean DEBUG_PACKAGE_INFO = false;
387    private static final boolean DEBUG_INTENT_MATCHING = false;
388    private static final boolean DEBUG_PACKAGE_SCANNING = false;
389    private static final boolean DEBUG_VERIFY = false;
390    private static final boolean DEBUG_FILTERS = false;
391    private static final boolean DEBUG_PERMISSIONS = false;
392    private static final boolean DEBUG_SHARED_LIBRARIES = false;
393
394    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
395    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
396    // user, but by default initialize to this.
397    public static final boolean DEBUG_DEXOPT = false;
398
399    private static final boolean DEBUG_ABI_SELECTION = false;
400    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
401    private static final boolean DEBUG_TRIAGED_MISSING = false;
402    private static final boolean DEBUG_APP_DATA = false;
403
404    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
405    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
406
407    private static final boolean HIDE_EPHEMERAL_APIS = false;
408
409    private static final boolean ENABLE_FREE_CACHE_V2 =
410            SystemProperties.getBoolean("fw.free_cache_v2", true);
411
412    private static final int RADIO_UID = Process.PHONE_UID;
413    private static final int LOG_UID = Process.LOG_UID;
414    private static final int NFC_UID = Process.NFC_UID;
415    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
416    private static final int SHELL_UID = Process.SHELL_UID;
417
418    // Cap the size of permission trees that 3rd party apps can define
419    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
420
421    // Suffix used during package installation when copying/moving
422    // package apks to install directory.
423    private static final String INSTALL_PACKAGE_SUFFIX = "-";
424
425    static final int SCAN_NO_DEX = 1<<1;
426    static final int SCAN_FORCE_DEX = 1<<2;
427    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
428    static final int SCAN_NEW_INSTALL = 1<<4;
429    static final int SCAN_UPDATE_TIME = 1<<5;
430    static final int SCAN_BOOTING = 1<<6;
431    static final int SCAN_TRUSTED_OVERLAY = 1<<7;
432    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8;
433    static final int SCAN_REPLACING = 1<<9;
434    static final int SCAN_REQUIRE_KNOWN = 1<<10;
435    static final int SCAN_MOVE = 1<<11;
436    static final int SCAN_INITIAL = 1<<12;
437    static final int SCAN_CHECK_ONLY = 1<<13;
438    static final int SCAN_DONT_KILL_APP = 1<<14;
439    static final int SCAN_IGNORE_FROZEN = 1<<15;
440    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16;
441    static final int SCAN_AS_INSTANT_APP = 1<<17;
442    static final int SCAN_AS_FULL_APP = 1<<18;
443    /** Should not be with the scan flags */
444    static final int FLAGS_REMOVE_CHATTY = 1<<31;
445
446    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
447
448    private static final int[] EMPTY_INT_ARRAY = new int[0];
449
450    private static final int TYPE_UNKNOWN = 0;
451    private static final int TYPE_ACTIVITY = 1;
452    private static final int TYPE_RECEIVER = 2;
453    private static final int TYPE_SERVICE = 3;
454    private static final int TYPE_PROVIDER = 4;
455    @IntDef(prefix = { "TYPE_" }, value = {
456            TYPE_UNKNOWN,
457            TYPE_ACTIVITY,
458            TYPE_RECEIVER,
459            TYPE_SERVICE,
460            TYPE_PROVIDER,
461    })
462    @Retention(RetentionPolicy.SOURCE)
463    public @interface ComponentType {}
464
465    /**
466     * Timeout (in milliseconds) after which the watchdog should declare that
467     * our handler thread is wedged.  The usual default for such things is one
468     * minute but we sometimes do very lengthy I/O operations on this thread,
469     * such as installing multi-gigabyte applications, so ours needs to be longer.
470     */
471    static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
472
473    /**
474     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
475     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
476     * settings entry if available, otherwise we use the hardcoded default.  If it's been
477     * more than this long since the last fstrim, we force one during the boot sequence.
478     *
479     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
480     * one gets run at the next available charging+idle time.  This final mandatory
481     * no-fstrim check kicks in only of the other scheduling criteria is never met.
482     */
483    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
484
485    /**
486     * Whether verification is enabled by default.
487     */
488    private static final boolean DEFAULT_VERIFY_ENABLE = true;
489
490    /**
491     * The default maximum time to wait for the verification agent to return in
492     * milliseconds.
493     */
494    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
495
496    /**
497     * The default response for package verification timeout.
498     *
499     * This can be either PackageManager.VERIFICATION_ALLOW or
500     * PackageManager.VERIFICATION_REJECT.
501     */
502    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
503
504    static final String PLATFORM_PACKAGE_NAME = "android";
505
506    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
507
508    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
509            DEFAULT_CONTAINER_PACKAGE,
510            "com.android.defcontainer.DefaultContainerService");
511
512    private static final String KILL_APP_REASON_GIDS_CHANGED =
513            "permission grant or revoke changed gids";
514
515    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
516            "permissions revoked";
517
518    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
519
520    private static final String PACKAGE_SCHEME = "package";
521
522    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
523
524    /** Permission grant: not grant the permission. */
525    private static final int GRANT_DENIED = 1;
526
527    /** Permission grant: grant the permission as an install permission. */
528    private static final int GRANT_INSTALL = 2;
529
530    /** Permission grant: grant the permission as a runtime one. */
531    private static final int GRANT_RUNTIME = 3;
532
533    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
534    private static final int GRANT_UPGRADE = 4;
535
536    /** Canonical intent used to identify what counts as a "web browser" app */
537    private static final Intent sBrowserIntent;
538    static {
539        sBrowserIntent = new Intent();
540        sBrowserIntent.setAction(Intent.ACTION_VIEW);
541        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
542        sBrowserIntent.setData(Uri.parse("http:"));
543    }
544
545    /**
546     * The set of all protected actions [i.e. those actions for which a high priority
547     * intent filter is disallowed].
548     */
549    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
550    static {
551        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
552        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
553        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
554        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
555    }
556
557    // Compilation reasons.
558    public static final int REASON_FIRST_BOOT = 0;
559    public static final int REASON_BOOT = 1;
560    public static final int REASON_INSTALL = 2;
561    public static final int REASON_BACKGROUND_DEXOPT = 3;
562    public static final int REASON_AB_OTA = 4;
563    public static final int REASON_INACTIVE_PACKAGE_DOWNGRADE = 5;
564
565    public static final int REASON_LAST = REASON_INACTIVE_PACKAGE_DOWNGRADE;
566
567    /** All dangerous permission names in the same order as the events in MetricsEvent */
568    private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList(
569            Manifest.permission.READ_CALENDAR,
570            Manifest.permission.WRITE_CALENDAR,
571            Manifest.permission.CAMERA,
572            Manifest.permission.READ_CONTACTS,
573            Manifest.permission.WRITE_CONTACTS,
574            Manifest.permission.GET_ACCOUNTS,
575            Manifest.permission.ACCESS_FINE_LOCATION,
576            Manifest.permission.ACCESS_COARSE_LOCATION,
577            Manifest.permission.RECORD_AUDIO,
578            Manifest.permission.READ_PHONE_STATE,
579            Manifest.permission.CALL_PHONE,
580            Manifest.permission.READ_CALL_LOG,
581            Manifest.permission.WRITE_CALL_LOG,
582            Manifest.permission.ADD_VOICEMAIL,
583            Manifest.permission.USE_SIP,
584            Manifest.permission.PROCESS_OUTGOING_CALLS,
585            Manifest.permission.READ_CELL_BROADCASTS,
586            Manifest.permission.BODY_SENSORS,
587            Manifest.permission.SEND_SMS,
588            Manifest.permission.RECEIVE_SMS,
589            Manifest.permission.READ_SMS,
590            Manifest.permission.RECEIVE_WAP_PUSH,
591            Manifest.permission.RECEIVE_MMS,
592            Manifest.permission.READ_EXTERNAL_STORAGE,
593            Manifest.permission.WRITE_EXTERNAL_STORAGE,
594            Manifest.permission.READ_PHONE_NUMBERS,
595            Manifest.permission.ANSWER_PHONE_CALLS);
596
597
598    /**
599     * Version number for the package parser cache. Increment this whenever the format or
600     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
601     */
602    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
603
604    /**
605     * Whether the package parser cache is enabled.
606     */
607    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
608
609    final ServiceThread mHandlerThread;
610
611    final PackageHandler mHandler;
612
613    private final ProcessLoggingHandler mProcessLoggingHandler;
614
615    /**
616     * Messages for {@link #mHandler} that need to wait for system ready before
617     * being dispatched.
618     */
619    private ArrayList<Message> mPostSystemReadyMessages;
620
621    final int mSdkVersion = Build.VERSION.SDK_INT;
622
623    final Context mContext;
624    final boolean mFactoryTest;
625    final boolean mOnlyCore;
626    final DisplayMetrics mMetrics;
627    final int mDefParseFlags;
628    final String[] mSeparateProcesses;
629    final boolean mIsUpgrade;
630    final boolean mIsPreNUpgrade;
631    final boolean mIsPreNMR1Upgrade;
632
633    // Have we told the Activity Manager to whitelist the default container service by uid yet?
634    @GuardedBy("mPackages")
635    boolean mDefaultContainerWhitelisted = false;
636
637    @GuardedBy("mPackages")
638    private boolean mDexOptDialogShown;
639
640    /** The location for ASEC container files on internal storage. */
641    final String mAsecInternalPath;
642
643    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
644    // LOCK HELD.  Can be called with mInstallLock held.
645    @GuardedBy("mInstallLock")
646    final Installer mInstaller;
647
648    /** Directory where installed third-party apps stored */
649    final File mAppInstallDir;
650
651    /**
652     * Directory to which applications installed internally have their
653     * 32 bit native libraries copied.
654     */
655    private File mAppLib32InstallDir;
656
657    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
658    // apps.
659    final File mDrmAppPrivateInstallDir;
660
661    // ----------------------------------------------------------------
662
663    // Lock for state used when installing and doing other long running
664    // operations.  Methods that must be called with this lock held have
665    // the suffix "LI".
666    final Object mInstallLock = new Object();
667
668    // ----------------------------------------------------------------
669
670    // Keys are String (package name), values are Package.  This also serves
671    // as the lock for the global state.  Methods that must be called with
672    // this lock held have the prefix "LP".
673    @GuardedBy("mPackages")
674    final ArrayMap<String, PackageParser.Package> mPackages =
675            new ArrayMap<String, PackageParser.Package>();
676
677    final ArrayMap<String, Set<String>> mKnownCodebase =
678            new ArrayMap<String, Set<String>>();
679
680    // Keys are isolated uids and values are the uid of the application
681    // that created the isolated proccess.
682    @GuardedBy("mPackages")
683    final SparseIntArray mIsolatedOwners = new SparseIntArray();
684
685    /**
686     * Tracks new system packages [received in an OTA] that we expect to
687     * find updated user-installed versions. Keys are package name, values
688     * are package location.
689     */
690    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
691    /**
692     * Tracks high priority intent filters for protected actions. During boot, certain
693     * filter actions are protected and should never be allowed to have a high priority
694     * intent filter for them. However, there is one, and only one exception -- the
695     * setup wizard. It must be able to define a high priority intent filter for these
696     * actions to ensure there are no escapes from the wizard. We need to delay processing
697     * of these during boot as we need to look at all of the system packages in order
698     * to know which component is the setup wizard.
699     */
700    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
701    /**
702     * Whether or not processing protected filters should be deferred.
703     */
704    private boolean mDeferProtectedFilters = true;
705
706    /**
707     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
708     */
709    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
710    /**
711     * Whether or not system app permissions should be promoted from install to runtime.
712     */
713    boolean mPromoteSystemApps;
714
715    @GuardedBy("mPackages")
716    final Settings mSettings;
717
718    /**
719     * Set of package names that are currently "frozen", which means active
720     * surgery is being done on the code/data for that package. The platform
721     * will refuse to launch frozen packages to avoid race conditions.
722     *
723     * @see PackageFreezer
724     */
725    @GuardedBy("mPackages")
726    final ArraySet<String> mFrozenPackages = new ArraySet<>();
727
728    final ProtectedPackages mProtectedPackages;
729
730    boolean mFirstBoot;
731
732    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
733
734    // System configuration read by SystemConfig.
735    final int[] mGlobalGids;
736    final SparseArray<ArraySet<String>> mSystemPermissions;
737    @GuardedBy("mAvailableFeatures")
738    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
739
740    // If mac_permissions.xml was found for seinfo labeling.
741    boolean mFoundPolicyFile;
742
743    private final InstantAppRegistry mInstantAppRegistry;
744
745    @GuardedBy("mPackages")
746    int mChangedPackagesSequenceNumber;
747    /**
748     * List of changed [installed, removed or updated] packages.
749     * mapping from user id -> sequence number -> package name
750     */
751    @GuardedBy("mPackages")
752    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
753    /**
754     * The sequence number of the last change to a package.
755     * mapping from user id -> package name -> sequence number
756     */
757    @GuardedBy("mPackages")
758    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
759
760    class PackageParserCallback implements PackageParser.Callback {
761        @Override public final boolean hasFeature(String feature) {
762            return PackageManagerService.this.hasSystemFeature(feature, 0);
763        }
764
765        final List<PackageParser.Package> getStaticOverlayPackagesLocked(
766                Collection<PackageParser.Package> allPackages, String targetPackageName) {
767            List<PackageParser.Package> overlayPackages = null;
768            for (PackageParser.Package p : allPackages) {
769                if (targetPackageName.equals(p.mOverlayTarget) && p.mIsStaticOverlay) {
770                    if (overlayPackages == null) {
771                        overlayPackages = new ArrayList<PackageParser.Package>();
772                    }
773                    overlayPackages.add(p);
774                }
775            }
776            if (overlayPackages != null) {
777                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
778                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
779                        return p1.mOverlayPriority - p2.mOverlayPriority;
780                    }
781                };
782                Collections.sort(overlayPackages, cmp);
783            }
784            return overlayPackages;
785        }
786
787        final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages,
788                String targetPackageName, String targetPath) {
789            if ("android".equals(targetPackageName)) {
790                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
791                // native AssetManager.
792                return null;
793            }
794            List<PackageParser.Package> overlayPackages =
795                    getStaticOverlayPackagesLocked(allPackages, targetPackageName);
796            if (overlayPackages == null || overlayPackages.isEmpty()) {
797                return null;
798            }
799            List<String> overlayPathList = null;
800            for (PackageParser.Package overlayPackage : overlayPackages) {
801                if (targetPath == null) {
802                    if (overlayPathList == null) {
803                        overlayPathList = new ArrayList<String>();
804                    }
805                    overlayPathList.add(overlayPackage.baseCodePath);
806                    continue;
807                }
808
809                try {
810                    // Creates idmaps for system to parse correctly the Android manifest of the
811                    // target package.
812                    //
813                    // OverlayManagerService will update each of them with a correct gid from its
814                    // target package app id.
815                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
816                            UserHandle.getSharedAppGid(
817                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
818                    if (overlayPathList == null) {
819                        overlayPathList = new ArrayList<String>();
820                    }
821                    overlayPathList.add(overlayPackage.baseCodePath);
822                } catch (InstallerException e) {
823                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
824                            overlayPackage.baseCodePath);
825                }
826            }
827            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
828        }
829
830        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
831            synchronized (mPackages) {
832                return getStaticOverlayPathsLocked(
833                        mPackages.values(), targetPackageName, targetPath);
834            }
835        }
836
837        @Override public final String[] getOverlayApks(String targetPackageName) {
838            return getStaticOverlayPaths(targetPackageName, null);
839        }
840
841        @Override public final String[] getOverlayPaths(String targetPackageName,
842                String targetPath) {
843            return getStaticOverlayPaths(targetPackageName, targetPath);
844        }
845    };
846
847    class ParallelPackageParserCallback extends PackageParserCallback {
848        List<PackageParser.Package> mOverlayPackages = null;
849
850        void findStaticOverlayPackages() {
851            synchronized (mPackages) {
852                for (PackageParser.Package p : mPackages.values()) {
853                    if (p.mIsStaticOverlay) {
854                        if (mOverlayPackages == null) {
855                            mOverlayPackages = new ArrayList<PackageParser.Package>();
856                        }
857                        mOverlayPackages.add(p);
858                    }
859                }
860            }
861        }
862
863        @Override
864        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
865            // We can trust mOverlayPackages without holding mPackages because package uninstall
866            // can't happen while running parallel parsing.
867            // Moreover holding mPackages on each parsing thread causes dead-lock.
868            return mOverlayPackages == null ? null :
869                    getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath);
870        }
871    }
872
873    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
874    final ParallelPackageParserCallback mParallelPackageParserCallback =
875            new ParallelPackageParserCallback();
876
877    public static final class SharedLibraryEntry {
878        public final @Nullable String path;
879        public final @Nullable String apk;
880        public final @NonNull SharedLibraryInfo info;
881
882        SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
883                String declaringPackageName, int declaringPackageVersionCode) {
884            path = _path;
885            apk = _apk;
886            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
887                    declaringPackageName, declaringPackageVersionCode), null);
888        }
889    }
890
891    // Currently known shared libraries.
892    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
893    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
894            new ArrayMap<>();
895
896    // All available activities, for your resolving pleasure.
897    final ActivityIntentResolver mActivities =
898            new ActivityIntentResolver();
899
900    // All available receivers, for your resolving pleasure.
901    final ActivityIntentResolver mReceivers =
902            new ActivityIntentResolver();
903
904    // All available services, for your resolving pleasure.
905    final ServiceIntentResolver mServices = new ServiceIntentResolver();
906
907    // All available providers, for your resolving pleasure.
908    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
909
910    // Mapping from provider base names (first directory in content URI codePath)
911    // to the provider information.
912    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
913            new ArrayMap<String, PackageParser.Provider>();
914
915    // Mapping from instrumentation class names to info about them.
916    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
917            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
918
919    // Mapping from permission names to info about them.
920    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
921            new ArrayMap<String, PackageParser.PermissionGroup>();
922
923    // Packages whose data we have transfered into another package, thus
924    // should no longer exist.
925    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
926
927    // Broadcast actions that are only available to the system.
928    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
929
930    /** List of packages waiting for verification. */
931    final SparseArray<PackageVerificationState> mPendingVerification
932            = new SparseArray<PackageVerificationState>();
933
934    /** Set of packages associated with each app op permission. */
935    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
936
937    final PackageInstallerService mInstallerService;
938
939    private final PackageDexOptimizer mPackageDexOptimizer;
940    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
941    // is used by other apps).
942    private final DexManager mDexManager;
943
944    private AtomicInteger mNextMoveId = new AtomicInteger();
945    private final MoveCallbacks mMoveCallbacks;
946
947    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
948
949    // Cache of users who need badging.
950    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
951
952    /** Token for keys in mPendingVerification. */
953    private int mPendingVerificationToken = 0;
954
955    volatile boolean mSystemReady;
956    volatile boolean mSafeMode;
957    volatile boolean mHasSystemUidErrors;
958    private volatile boolean mEphemeralAppsDisabled;
959
960    ApplicationInfo mAndroidApplication;
961    final ActivityInfo mResolveActivity = new ActivityInfo();
962    final ResolveInfo mResolveInfo = new ResolveInfo();
963    ComponentName mResolveComponentName;
964    PackageParser.Package mPlatformPackage;
965    ComponentName mCustomResolverComponentName;
966
967    boolean mResolverReplaced = false;
968
969    private final @Nullable ComponentName mIntentFilterVerifierComponent;
970    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
971
972    private int mIntentFilterVerificationToken = 0;
973
974    /** The service connection to the ephemeral resolver */
975    final EphemeralResolverConnection mInstantAppResolverConnection;
976    /** Component used to show resolver settings for Instant Apps */
977    final ComponentName mInstantAppResolverSettingsComponent;
978
979    /** Activity used to install instant applications */
980    ActivityInfo mInstantAppInstallerActivity;
981    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
982
983    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
984            = new SparseArray<IntentFilterVerificationState>();
985
986    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
987
988    // List of packages names to keep cached, even if they are uninstalled for all users
989    private List<String> mKeepUninstalledPackages;
990
991    private UserManagerInternal mUserManagerInternal;
992
993    private DeviceIdleController.LocalService mDeviceIdleController;
994
995    private File mCacheDir;
996
997    private ArraySet<String> mPrivappPermissionsViolations;
998
999    private Future<?> mPrepareAppDataFuture;
1000
1001    private static class IFVerificationParams {
1002        PackageParser.Package pkg;
1003        boolean replacing;
1004        int userId;
1005        int verifierUid;
1006
1007        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1008                int _userId, int _verifierUid) {
1009            pkg = _pkg;
1010            replacing = _replacing;
1011            userId = _userId;
1012            replacing = _replacing;
1013            verifierUid = _verifierUid;
1014        }
1015    }
1016
1017    private interface IntentFilterVerifier<T extends IntentFilter> {
1018        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1019                                               T filter, String packageName);
1020        void startVerifications(int userId);
1021        void receiveVerificationResponse(int verificationId);
1022    }
1023
1024    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1025        private Context mContext;
1026        private ComponentName mIntentFilterVerifierComponent;
1027        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1028
1029        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1030            mContext = context;
1031            mIntentFilterVerifierComponent = verifierComponent;
1032        }
1033
1034        private String getDefaultScheme() {
1035            return IntentFilter.SCHEME_HTTPS;
1036        }
1037
1038        @Override
1039        public void startVerifications(int userId) {
1040            // Launch verifications requests
1041            int count = mCurrentIntentFilterVerifications.size();
1042            for (int n=0; n<count; n++) {
1043                int verificationId = mCurrentIntentFilterVerifications.get(n);
1044                final IntentFilterVerificationState ivs =
1045                        mIntentFilterVerificationStates.get(verificationId);
1046
1047                String packageName = ivs.getPackageName();
1048
1049                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1050                final int filterCount = filters.size();
1051                ArraySet<String> domainsSet = new ArraySet<>();
1052                for (int m=0; m<filterCount; m++) {
1053                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1054                    domainsSet.addAll(filter.getHostsList());
1055                }
1056                synchronized (mPackages) {
1057                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1058                            packageName, domainsSet) != null) {
1059                        scheduleWriteSettingsLocked();
1060                    }
1061                }
1062                sendVerificationRequest(userId, verificationId, ivs);
1063            }
1064            mCurrentIntentFilterVerifications.clear();
1065        }
1066
1067        private void sendVerificationRequest(int userId, int verificationId,
1068                IntentFilterVerificationState ivs) {
1069
1070            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1071            verificationIntent.putExtra(
1072                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1073                    verificationId);
1074            verificationIntent.putExtra(
1075                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1076                    getDefaultScheme());
1077            verificationIntent.putExtra(
1078                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1079                    ivs.getHostsString());
1080            verificationIntent.putExtra(
1081                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1082                    ivs.getPackageName());
1083            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1084            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1085
1086            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1087            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1088                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1089                    userId, false, "intent filter verifier");
1090
1091            UserHandle user = new UserHandle(userId);
1092            mContext.sendBroadcastAsUser(verificationIntent, user);
1093            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1094                    "Sending IntentFilter verification broadcast");
1095        }
1096
1097        public void receiveVerificationResponse(int verificationId) {
1098            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1099
1100            final boolean verified = ivs.isVerified();
1101
1102            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1103            final int count = filters.size();
1104            if (DEBUG_DOMAIN_VERIFICATION) {
1105                Slog.i(TAG, "Received verification response " + verificationId
1106                        + " for " + count + " filters, verified=" + verified);
1107            }
1108            for (int n=0; n<count; n++) {
1109                PackageParser.ActivityIntentInfo filter = filters.get(n);
1110                filter.setVerified(verified);
1111
1112                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1113                        + " verified with result:" + verified + " and hosts:"
1114                        + ivs.getHostsString());
1115            }
1116
1117            mIntentFilterVerificationStates.remove(verificationId);
1118
1119            final String packageName = ivs.getPackageName();
1120            IntentFilterVerificationInfo ivi = null;
1121
1122            synchronized (mPackages) {
1123                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1124            }
1125            if (ivi == null) {
1126                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1127                        + verificationId + " packageName:" + packageName);
1128                return;
1129            }
1130            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1131                    "Updating IntentFilterVerificationInfo for package " + packageName
1132                            +" verificationId:" + verificationId);
1133
1134            synchronized (mPackages) {
1135                if (verified) {
1136                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1137                } else {
1138                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1139                }
1140                scheduleWriteSettingsLocked();
1141
1142                final int userId = ivs.getUserId();
1143                if (userId != UserHandle.USER_ALL) {
1144                    final int userStatus =
1145                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1146
1147                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1148                    boolean needUpdate = false;
1149
1150                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1151                    // already been set by the User thru the Disambiguation dialog
1152                    switch (userStatus) {
1153                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1154                            if (verified) {
1155                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1156                            } else {
1157                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1158                            }
1159                            needUpdate = true;
1160                            break;
1161
1162                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1163                            if (verified) {
1164                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1165                                needUpdate = true;
1166                            }
1167                            break;
1168
1169                        default:
1170                            // Nothing to do
1171                    }
1172
1173                    if (needUpdate) {
1174                        mSettings.updateIntentFilterVerificationStatusLPw(
1175                                packageName, updatedStatus, userId);
1176                        scheduleWritePackageRestrictionsLocked(userId);
1177                    }
1178                }
1179            }
1180        }
1181
1182        @Override
1183        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1184                    ActivityIntentInfo filter, String packageName) {
1185            if (!hasValidDomains(filter)) {
1186                return false;
1187            }
1188            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1189            if (ivs == null) {
1190                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1191                        packageName);
1192            }
1193            if (DEBUG_DOMAIN_VERIFICATION) {
1194                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1195            }
1196            ivs.addFilter(filter);
1197            return true;
1198        }
1199
1200        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1201                int userId, int verificationId, String packageName) {
1202            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1203                    verifierUid, userId, packageName);
1204            ivs.setPendingState();
1205            synchronized (mPackages) {
1206                mIntentFilterVerificationStates.append(verificationId, ivs);
1207                mCurrentIntentFilterVerifications.add(verificationId);
1208            }
1209            return ivs;
1210        }
1211    }
1212
1213    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1214        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1215                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1216                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1217    }
1218
1219    // Set of pending broadcasts for aggregating enable/disable of components.
1220    static class PendingPackageBroadcasts {
1221        // for each user id, a map of <package name -> components within that package>
1222        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1223
1224        public PendingPackageBroadcasts() {
1225            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1226        }
1227
1228        public ArrayList<String> get(int userId, String packageName) {
1229            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1230            return packages.get(packageName);
1231        }
1232
1233        public void put(int userId, String packageName, ArrayList<String> components) {
1234            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1235            packages.put(packageName, components);
1236        }
1237
1238        public void remove(int userId, String packageName) {
1239            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1240            if (packages != null) {
1241                packages.remove(packageName);
1242            }
1243        }
1244
1245        public void remove(int userId) {
1246            mUidMap.remove(userId);
1247        }
1248
1249        public int userIdCount() {
1250            return mUidMap.size();
1251        }
1252
1253        public int userIdAt(int n) {
1254            return mUidMap.keyAt(n);
1255        }
1256
1257        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1258            return mUidMap.get(userId);
1259        }
1260
1261        public int size() {
1262            // total number of pending broadcast entries across all userIds
1263            int num = 0;
1264            for (int i = 0; i< mUidMap.size(); i++) {
1265                num += mUidMap.valueAt(i).size();
1266            }
1267            return num;
1268        }
1269
1270        public void clear() {
1271            mUidMap.clear();
1272        }
1273
1274        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1275            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1276            if (map == null) {
1277                map = new ArrayMap<String, ArrayList<String>>();
1278                mUidMap.put(userId, map);
1279            }
1280            return map;
1281        }
1282    }
1283    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1284
1285    // Service Connection to remote media container service to copy
1286    // package uri's from external media onto secure containers
1287    // or internal storage.
1288    private IMediaContainerService mContainerService = null;
1289
1290    static final int SEND_PENDING_BROADCAST = 1;
1291    static final int MCS_BOUND = 3;
1292    static final int END_COPY = 4;
1293    static final int INIT_COPY = 5;
1294    static final int MCS_UNBIND = 6;
1295    static final int START_CLEANING_PACKAGE = 7;
1296    static final int FIND_INSTALL_LOC = 8;
1297    static final int POST_INSTALL = 9;
1298    static final int MCS_RECONNECT = 10;
1299    static final int MCS_GIVE_UP = 11;
1300    static final int UPDATED_MEDIA_STATUS = 12;
1301    static final int WRITE_SETTINGS = 13;
1302    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1303    static final int PACKAGE_VERIFIED = 15;
1304    static final int CHECK_PENDING_VERIFICATION = 16;
1305    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1306    static final int INTENT_FILTER_VERIFIED = 18;
1307    static final int WRITE_PACKAGE_LIST = 19;
1308    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1309
1310    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1311
1312    // Delay time in millisecs
1313    static final int BROADCAST_DELAY = 10 * 1000;
1314
1315    private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1316            2 * 60 * 60 * 1000L; /* two hours */
1317
1318    static UserManagerService sUserManager;
1319
1320    // Stores a list of users whose package restrictions file needs to be updated
1321    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1322
1323    final private DefaultContainerConnection mDefContainerConn =
1324            new DefaultContainerConnection();
1325    class DefaultContainerConnection implements ServiceConnection {
1326        public void onServiceConnected(ComponentName name, IBinder service) {
1327            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1328            final IMediaContainerService imcs = IMediaContainerService.Stub
1329                    .asInterface(Binder.allowBlocking(service));
1330            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1331        }
1332
1333        public void onServiceDisconnected(ComponentName name) {
1334            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1335        }
1336    }
1337
1338    // Recordkeeping of restore-after-install operations that are currently in flight
1339    // between the Package Manager and the Backup Manager
1340    static class PostInstallData {
1341        public InstallArgs args;
1342        public PackageInstalledInfo res;
1343
1344        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1345            args = _a;
1346            res = _r;
1347        }
1348    }
1349
1350    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1351    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1352
1353    // XML tags for backup/restore of various bits of state
1354    private static final String TAG_PREFERRED_BACKUP = "pa";
1355    private static final String TAG_DEFAULT_APPS = "da";
1356    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1357
1358    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1359    private static final String TAG_ALL_GRANTS = "rt-grants";
1360    private static final String TAG_GRANT = "grant";
1361    private static final String ATTR_PACKAGE_NAME = "pkg";
1362
1363    private static final String TAG_PERMISSION = "perm";
1364    private static final String ATTR_PERMISSION_NAME = "name";
1365    private static final String ATTR_IS_GRANTED = "g";
1366    private static final String ATTR_USER_SET = "set";
1367    private static final String ATTR_USER_FIXED = "fixed";
1368    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1369
1370    // System/policy permission grants are not backed up
1371    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1372            FLAG_PERMISSION_POLICY_FIXED
1373            | FLAG_PERMISSION_SYSTEM_FIXED
1374            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1375
1376    // And we back up these user-adjusted states
1377    private static final int USER_RUNTIME_GRANT_MASK =
1378            FLAG_PERMISSION_USER_SET
1379            | FLAG_PERMISSION_USER_FIXED
1380            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1381
1382    final @Nullable String mRequiredVerifierPackage;
1383    final @NonNull String mRequiredInstallerPackage;
1384    final @NonNull String mRequiredUninstallerPackage;
1385    final @Nullable String mSetupWizardPackage;
1386    final @Nullable String mStorageManagerPackage;
1387    final @NonNull String mServicesSystemSharedLibraryPackageName;
1388    final @NonNull String mSharedSystemSharedLibraryPackageName;
1389
1390    final boolean mPermissionReviewRequired;
1391
1392    private final PackageUsage mPackageUsage = new PackageUsage();
1393    private final CompilerStats mCompilerStats = new CompilerStats();
1394
1395    class PackageHandler extends Handler {
1396        private boolean mBound = false;
1397        final ArrayList<HandlerParams> mPendingInstalls =
1398            new ArrayList<HandlerParams>();
1399
1400        private boolean connectToService() {
1401            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1402                    " DefaultContainerService");
1403            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1404            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1405            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1406                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1407                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1408                mBound = true;
1409                return true;
1410            }
1411            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1412            return false;
1413        }
1414
1415        private void disconnectService() {
1416            mContainerService = null;
1417            mBound = false;
1418            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1419            mContext.unbindService(mDefContainerConn);
1420            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1421        }
1422
1423        PackageHandler(Looper looper) {
1424            super(looper);
1425        }
1426
1427        public void handleMessage(Message msg) {
1428            try {
1429                doHandleMessage(msg);
1430            } finally {
1431                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1432            }
1433        }
1434
1435        void doHandleMessage(Message msg) {
1436            switch (msg.what) {
1437                case INIT_COPY: {
1438                    HandlerParams params = (HandlerParams) msg.obj;
1439                    int idx = mPendingInstalls.size();
1440                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1441                    // If a bind was already initiated we dont really
1442                    // need to do anything. The pending install
1443                    // will be processed later on.
1444                    if (!mBound) {
1445                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1446                                System.identityHashCode(mHandler));
1447                        // If this is the only one pending we might
1448                        // have to bind to the service again.
1449                        if (!connectToService()) {
1450                            Slog.e(TAG, "Failed to bind to media container service");
1451                            params.serviceError();
1452                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1453                                    System.identityHashCode(mHandler));
1454                            if (params.traceMethod != null) {
1455                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1456                                        params.traceCookie);
1457                            }
1458                            return;
1459                        } else {
1460                            // Once we bind to the service, the first
1461                            // pending request will be processed.
1462                            mPendingInstalls.add(idx, params);
1463                        }
1464                    } else {
1465                        mPendingInstalls.add(idx, params);
1466                        // Already bound to the service. Just make
1467                        // sure we trigger off processing the first request.
1468                        if (idx == 0) {
1469                            mHandler.sendEmptyMessage(MCS_BOUND);
1470                        }
1471                    }
1472                    break;
1473                }
1474                case MCS_BOUND: {
1475                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1476                    if (msg.obj != null) {
1477                        mContainerService = (IMediaContainerService) msg.obj;
1478                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1479                                System.identityHashCode(mHandler));
1480                    }
1481                    if (mContainerService == null) {
1482                        if (!mBound) {
1483                            // Something seriously wrong since we are not bound and we are not
1484                            // waiting for connection. Bail out.
1485                            Slog.e(TAG, "Cannot bind to media container service");
1486                            for (HandlerParams params : mPendingInstalls) {
1487                                // Indicate service bind error
1488                                params.serviceError();
1489                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1490                                        System.identityHashCode(params));
1491                                if (params.traceMethod != null) {
1492                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1493                                            params.traceMethod, params.traceCookie);
1494                                }
1495                                return;
1496                            }
1497                            mPendingInstalls.clear();
1498                        } else {
1499                            Slog.w(TAG, "Waiting to connect to media container service");
1500                        }
1501                    } else if (mPendingInstalls.size() > 0) {
1502                        HandlerParams params = mPendingInstalls.get(0);
1503                        if (params != null) {
1504                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1505                                    System.identityHashCode(params));
1506                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1507                            if (params.startCopy()) {
1508                                // We are done...  look for more work or to
1509                                // go idle.
1510                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1511                                        "Checking for more work or unbind...");
1512                                // Delete pending install
1513                                if (mPendingInstalls.size() > 0) {
1514                                    mPendingInstalls.remove(0);
1515                                }
1516                                if (mPendingInstalls.size() == 0) {
1517                                    if (mBound) {
1518                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1519                                                "Posting delayed MCS_UNBIND");
1520                                        removeMessages(MCS_UNBIND);
1521                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1522                                        // Unbind after a little delay, to avoid
1523                                        // continual thrashing.
1524                                        sendMessageDelayed(ubmsg, 10000);
1525                                    }
1526                                } else {
1527                                    // There are more pending requests in queue.
1528                                    // Just post MCS_BOUND message to trigger processing
1529                                    // of next pending install.
1530                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1531                                            "Posting MCS_BOUND for next work");
1532                                    mHandler.sendEmptyMessage(MCS_BOUND);
1533                                }
1534                            }
1535                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1536                        }
1537                    } else {
1538                        // Should never happen ideally.
1539                        Slog.w(TAG, "Empty queue");
1540                    }
1541                    break;
1542                }
1543                case MCS_RECONNECT: {
1544                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1545                    if (mPendingInstalls.size() > 0) {
1546                        if (mBound) {
1547                            disconnectService();
1548                        }
1549                        if (!connectToService()) {
1550                            Slog.e(TAG, "Failed to bind to media container service");
1551                            for (HandlerParams params : mPendingInstalls) {
1552                                // Indicate service bind error
1553                                params.serviceError();
1554                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1555                                        System.identityHashCode(params));
1556                            }
1557                            mPendingInstalls.clear();
1558                        }
1559                    }
1560                    break;
1561                }
1562                case MCS_UNBIND: {
1563                    // If there is no actual work left, then time to unbind.
1564                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1565
1566                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1567                        if (mBound) {
1568                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1569
1570                            disconnectService();
1571                        }
1572                    } else if (mPendingInstalls.size() > 0) {
1573                        // There are more pending requests in queue.
1574                        // Just post MCS_BOUND message to trigger processing
1575                        // of next pending install.
1576                        mHandler.sendEmptyMessage(MCS_BOUND);
1577                    }
1578
1579                    break;
1580                }
1581                case MCS_GIVE_UP: {
1582                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1583                    HandlerParams params = mPendingInstalls.remove(0);
1584                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1585                            System.identityHashCode(params));
1586                    break;
1587                }
1588                case SEND_PENDING_BROADCAST: {
1589                    String packages[];
1590                    ArrayList<String> components[];
1591                    int size = 0;
1592                    int uids[];
1593                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1594                    synchronized (mPackages) {
1595                        if (mPendingBroadcasts == null) {
1596                            return;
1597                        }
1598                        size = mPendingBroadcasts.size();
1599                        if (size <= 0) {
1600                            // Nothing to be done. Just return
1601                            return;
1602                        }
1603                        packages = new String[size];
1604                        components = new ArrayList[size];
1605                        uids = new int[size];
1606                        int i = 0;  // filling out the above arrays
1607
1608                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1609                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1610                            Iterator<Map.Entry<String, ArrayList<String>>> it
1611                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1612                                            .entrySet().iterator();
1613                            while (it.hasNext() && i < size) {
1614                                Map.Entry<String, ArrayList<String>> ent = it.next();
1615                                packages[i] = ent.getKey();
1616                                components[i] = ent.getValue();
1617                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1618                                uids[i] = (ps != null)
1619                                        ? UserHandle.getUid(packageUserId, ps.appId)
1620                                        : -1;
1621                                i++;
1622                            }
1623                        }
1624                        size = i;
1625                        mPendingBroadcasts.clear();
1626                    }
1627                    // Send broadcasts
1628                    for (int i = 0; i < size; i++) {
1629                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1630                    }
1631                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1632                    break;
1633                }
1634                case START_CLEANING_PACKAGE: {
1635                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1636                    final String packageName = (String)msg.obj;
1637                    final int userId = msg.arg1;
1638                    final boolean andCode = msg.arg2 != 0;
1639                    synchronized (mPackages) {
1640                        if (userId == UserHandle.USER_ALL) {
1641                            int[] users = sUserManager.getUserIds();
1642                            for (int user : users) {
1643                                mSettings.addPackageToCleanLPw(
1644                                        new PackageCleanItem(user, packageName, andCode));
1645                            }
1646                        } else {
1647                            mSettings.addPackageToCleanLPw(
1648                                    new PackageCleanItem(userId, packageName, andCode));
1649                        }
1650                    }
1651                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1652                    startCleaningPackages();
1653                } break;
1654                case POST_INSTALL: {
1655                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1656
1657                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1658                    final boolean didRestore = (msg.arg2 != 0);
1659                    mRunningInstalls.delete(msg.arg1);
1660
1661                    if (data != null) {
1662                        InstallArgs args = data.args;
1663                        PackageInstalledInfo parentRes = data.res;
1664
1665                        final boolean grantPermissions = (args.installFlags
1666                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1667                        final boolean killApp = (args.installFlags
1668                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1669                        final String[] grantedPermissions = args.installGrantPermissions;
1670
1671                        // Handle the parent package
1672                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1673                                grantedPermissions, didRestore, args.installerPackageName,
1674                                args.observer);
1675
1676                        // Handle the child packages
1677                        final int childCount = (parentRes.addedChildPackages != null)
1678                                ? parentRes.addedChildPackages.size() : 0;
1679                        for (int i = 0; i < childCount; i++) {
1680                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1681                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1682                                    grantedPermissions, false, args.installerPackageName,
1683                                    args.observer);
1684                        }
1685
1686                        // Log tracing if needed
1687                        if (args.traceMethod != null) {
1688                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1689                                    args.traceCookie);
1690                        }
1691                    } else {
1692                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1693                    }
1694
1695                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1696                } break;
1697                case UPDATED_MEDIA_STATUS: {
1698                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1699                    boolean reportStatus = msg.arg1 == 1;
1700                    boolean doGc = msg.arg2 == 1;
1701                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1702                    if (doGc) {
1703                        // Force a gc to clear up stale containers.
1704                        Runtime.getRuntime().gc();
1705                    }
1706                    if (msg.obj != null) {
1707                        @SuppressWarnings("unchecked")
1708                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1709                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1710                        // Unload containers
1711                        unloadAllContainers(args);
1712                    }
1713                    if (reportStatus) {
1714                        try {
1715                            if (DEBUG_SD_INSTALL) Log.i(TAG,
1716                                    "Invoking StorageManagerService call back");
1717                            PackageHelper.getStorageManager().finishMediaUpdate();
1718                        } catch (RemoteException e) {
1719                            Log.e(TAG, "StorageManagerService not running?");
1720                        }
1721                    }
1722                } break;
1723                case WRITE_SETTINGS: {
1724                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1725                    synchronized (mPackages) {
1726                        removeMessages(WRITE_SETTINGS);
1727                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1728                        mSettings.writeLPr();
1729                        mDirtyUsers.clear();
1730                    }
1731                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1732                } break;
1733                case WRITE_PACKAGE_RESTRICTIONS: {
1734                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1735                    synchronized (mPackages) {
1736                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1737                        for (int userId : mDirtyUsers) {
1738                            mSettings.writePackageRestrictionsLPr(userId);
1739                        }
1740                        mDirtyUsers.clear();
1741                    }
1742                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1743                } break;
1744                case WRITE_PACKAGE_LIST: {
1745                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1746                    synchronized (mPackages) {
1747                        removeMessages(WRITE_PACKAGE_LIST);
1748                        mSettings.writePackageListLPr(msg.arg1);
1749                    }
1750                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1751                } break;
1752                case CHECK_PENDING_VERIFICATION: {
1753                    final int verificationId = msg.arg1;
1754                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1755
1756                    if ((state != null) && !state.timeoutExtended()) {
1757                        final InstallArgs args = state.getInstallArgs();
1758                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1759
1760                        Slog.i(TAG, "Verification timed out for " + originUri);
1761                        mPendingVerification.remove(verificationId);
1762
1763                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1764
1765                        final UserHandle user = args.getUser();
1766                        if (getDefaultVerificationResponse(user)
1767                                == PackageManager.VERIFICATION_ALLOW) {
1768                            Slog.i(TAG, "Continuing with installation of " + originUri);
1769                            state.setVerifierResponse(Binder.getCallingUid(),
1770                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1771                            broadcastPackageVerified(verificationId, originUri,
1772                                    PackageManager.VERIFICATION_ALLOW, user);
1773                            try {
1774                                ret = args.copyApk(mContainerService, true);
1775                            } catch (RemoteException e) {
1776                                Slog.e(TAG, "Could not contact the ContainerService");
1777                            }
1778                        } else {
1779                            broadcastPackageVerified(verificationId, originUri,
1780                                    PackageManager.VERIFICATION_REJECT, user);
1781                        }
1782
1783                        Trace.asyncTraceEnd(
1784                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1785
1786                        processPendingInstall(args, ret);
1787                        mHandler.sendEmptyMessage(MCS_UNBIND);
1788                    }
1789                    break;
1790                }
1791                case PACKAGE_VERIFIED: {
1792                    final int verificationId = msg.arg1;
1793
1794                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1795                    if (state == null) {
1796                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1797                        break;
1798                    }
1799
1800                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1801
1802                    state.setVerifierResponse(response.callerUid, response.code);
1803
1804                    if (state.isVerificationComplete()) {
1805                        mPendingVerification.remove(verificationId);
1806
1807                        final InstallArgs args = state.getInstallArgs();
1808                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1809
1810                        int ret;
1811                        if (state.isInstallAllowed()) {
1812                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1813                            broadcastPackageVerified(verificationId, originUri,
1814                                    response.code, state.getInstallArgs().getUser());
1815                            try {
1816                                ret = args.copyApk(mContainerService, true);
1817                            } catch (RemoteException e) {
1818                                Slog.e(TAG, "Could not contact the ContainerService");
1819                            }
1820                        } else {
1821                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1822                        }
1823
1824                        Trace.asyncTraceEnd(
1825                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1826
1827                        processPendingInstall(args, ret);
1828                        mHandler.sendEmptyMessage(MCS_UNBIND);
1829                    }
1830
1831                    break;
1832                }
1833                case START_INTENT_FILTER_VERIFICATIONS: {
1834                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1835                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1836                            params.replacing, params.pkg);
1837                    break;
1838                }
1839                case INTENT_FILTER_VERIFIED: {
1840                    final int verificationId = msg.arg1;
1841
1842                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1843                            verificationId);
1844                    if (state == null) {
1845                        Slog.w(TAG, "Invalid IntentFilter verification token "
1846                                + verificationId + " received");
1847                        break;
1848                    }
1849
1850                    final int userId = state.getUserId();
1851
1852                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1853                            "Processing IntentFilter verification with token:"
1854                            + verificationId + " and userId:" + userId);
1855
1856                    final IntentFilterVerificationResponse response =
1857                            (IntentFilterVerificationResponse) msg.obj;
1858
1859                    state.setVerifierResponse(response.callerUid, response.code);
1860
1861                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1862                            "IntentFilter verification with token:" + verificationId
1863                            + " and userId:" + userId
1864                            + " is settings verifier response with response code:"
1865                            + response.code);
1866
1867                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1868                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1869                                + response.getFailedDomainsString());
1870                    }
1871
1872                    if (state.isVerificationComplete()) {
1873                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1874                    } else {
1875                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1876                                "IntentFilter verification with token:" + verificationId
1877                                + " was not said to be complete");
1878                    }
1879
1880                    break;
1881                }
1882                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1883                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1884                            mInstantAppResolverConnection,
1885                            (InstantAppRequest) msg.obj,
1886                            mInstantAppInstallerActivity,
1887                            mHandler);
1888                }
1889            }
1890        }
1891    }
1892
1893    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1894            boolean killApp, String[] grantedPermissions,
1895            boolean launchedForRestore, String installerPackage,
1896            IPackageInstallObserver2 installObserver) {
1897        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1898            // Send the removed broadcasts
1899            if (res.removedInfo != null) {
1900                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1901            }
1902
1903            // Now that we successfully installed the package, grant runtime
1904            // permissions if requested before broadcasting the install. Also
1905            // for legacy apps in permission review mode we clear the permission
1906            // review flag which is used to emulate runtime permissions for
1907            // legacy apps.
1908            if (grantPermissions) {
1909                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1910            }
1911
1912            final boolean update = res.removedInfo != null
1913                    && res.removedInfo.removedPackage != null;
1914            final String origInstallerPackageName = res.removedInfo != null
1915                    ? res.removedInfo.installerPackageName : null;
1916
1917            // If this is the first time we have child packages for a disabled privileged
1918            // app that had no children, we grant requested runtime permissions to the new
1919            // children if the parent on the system image had them already granted.
1920            if (res.pkg.parentPackage != null) {
1921                synchronized (mPackages) {
1922                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1923                }
1924            }
1925
1926            synchronized (mPackages) {
1927                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1928            }
1929
1930            final String packageName = res.pkg.applicationInfo.packageName;
1931
1932            // Determine the set of users who are adding this package for
1933            // the first time vs. those who are seeing an update.
1934            int[] firstUsers = EMPTY_INT_ARRAY;
1935            int[] updateUsers = EMPTY_INT_ARRAY;
1936            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1937            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1938            for (int newUser : res.newUsers) {
1939                if (ps.getInstantApp(newUser)) {
1940                    continue;
1941                }
1942                if (allNewUsers) {
1943                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1944                    continue;
1945                }
1946                boolean isNew = true;
1947                for (int origUser : res.origUsers) {
1948                    if (origUser == newUser) {
1949                        isNew = false;
1950                        break;
1951                    }
1952                }
1953                if (isNew) {
1954                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1955                } else {
1956                    updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1957                }
1958            }
1959
1960            // Send installed broadcasts if the package is not a static shared lib.
1961            if (res.pkg.staticSharedLibName == null) {
1962                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1963
1964                // Send added for users that see the package for the first time
1965                // sendPackageAddedForNewUsers also deals with system apps
1966                int appId = UserHandle.getAppId(res.uid);
1967                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1968                sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers);
1969
1970                // Send added for users that don't see the package for the first time
1971                Bundle extras = new Bundle(1);
1972                extras.putInt(Intent.EXTRA_UID, res.uid);
1973                if (update) {
1974                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1975                }
1976                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1977                        extras, 0 /*flags*/,
1978                        null /*targetPackage*/, null /*finishedReceiver*/, updateUsers);
1979                if (origInstallerPackageName != null) {
1980                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1981                            extras, 0 /*flags*/,
1982                            origInstallerPackageName, null /*finishedReceiver*/, updateUsers);
1983                }
1984
1985                // Send replaced for users that don't see the package for the first time
1986                if (update) {
1987                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1988                            packageName, extras, 0 /*flags*/,
1989                            null /*targetPackage*/, null /*finishedReceiver*/,
1990                            updateUsers);
1991                    if (origInstallerPackageName != null) {
1992                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
1993                                extras, 0 /*flags*/,
1994                                origInstallerPackageName, null /*finishedReceiver*/, updateUsers);
1995                    }
1996                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1997                            null /*package*/, null /*extras*/, 0 /*flags*/,
1998                            packageName /*targetPackage*/,
1999                            null /*finishedReceiver*/, updateUsers);
2000                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
2001                    // First-install and we did a restore, so we're responsible for the
2002                    // first-launch broadcast.
2003                    if (DEBUG_BACKUP) {
2004                        Slog.i(TAG, "Post-restore of " + packageName
2005                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
2006                    }
2007                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
2008                }
2009
2010                // Send broadcast package appeared if forward locked/external for all users
2011                // treat asec-hosted packages like removable media on upgrade
2012                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2013                    if (DEBUG_INSTALL) {
2014                        Slog.i(TAG, "upgrading pkg " + res.pkg
2015                                + " is ASEC-hosted -> AVAILABLE");
2016                    }
2017                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2018                    ArrayList<String> pkgList = new ArrayList<>(1);
2019                    pkgList.add(packageName);
2020                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2021                }
2022            }
2023
2024            // Work that needs to happen on first install within each user
2025            if (firstUsers != null && firstUsers.length > 0) {
2026                synchronized (mPackages) {
2027                    for (int userId : firstUsers) {
2028                        // If this app is a browser and it's newly-installed for some
2029                        // users, clear any default-browser state in those users. The
2030                        // app's nature doesn't depend on the user, so we can just check
2031                        // its browser nature in any user and generalize.
2032                        if (packageIsBrowser(packageName, userId)) {
2033                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2034                        }
2035
2036                        // We may also need to apply pending (restored) runtime
2037                        // permission grants within these users.
2038                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2039                    }
2040                }
2041            }
2042
2043            // Log current value of "unknown sources" setting
2044            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2045                    getUnknownSourcesSettings());
2046
2047            // Remove the replaced package's older resources safely now
2048            // We delete after a gc for applications  on sdcard.
2049            if (res.removedInfo != null && res.removedInfo.args != null) {
2050                Runtime.getRuntime().gc();
2051                synchronized (mInstallLock) {
2052                    res.removedInfo.args.doPostDeleteLI(true);
2053                }
2054            } else {
2055                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2056                // and not block here.
2057                VMRuntime.getRuntime().requestConcurrentGC();
2058            }
2059
2060            // Notify DexManager that the package was installed for new users.
2061            // The updated users should already be indexed and the package code paths
2062            // should not change.
2063            // Don't notify the manager for ephemeral apps as they are not expected to
2064            // survive long enough to benefit of background optimizations.
2065            for (int userId : firstUsers) {
2066                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2067                // There's a race currently where some install events may interleave with an uninstall.
2068                // This can lead to package info being null (b/36642664).
2069                if (info != null) {
2070                    mDexManager.notifyPackageInstalled(info, userId);
2071                }
2072            }
2073        }
2074
2075        // If someone is watching installs - notify them
2076        if (installObserver != null) {
2077            try {
2078                Bundle extras = extrasForInstallResult(res);
2079                installObserver.onPackageInstalled(res.name, res.returnCode,
2080                        res.returnMsg, extras);
2081            } catch (RemoteException e) {
2082                Slog.i(TAG, "Observer no longer exists.");
2083            }
2084        }
2085    }
2086
2087    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
2088            PackageParser.Package pkg) {
2089        if (pkg.parentPackage == null) {
2090            return;
2091        }
2092        if (pkg.requestedPermissions == null) {
2093            return;
2094        }
2095        final PackageSetting disabledSysParentPs = mSettings
2096                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
2097        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
2098                || !disabledSysParentPs.isPrivileged()
2099                || (disabledSysParentPs.childPackageNames != null
2100                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
2101            return;
2102        }
2103        final int[] allUserIds = sUserManager.getUserIds();
2104        final int permCount = pkg.requestedPermissions.size();
2105        for (int i = 0; i < permCount; i++) {
2106            String permission = pkg.requestedPermissions.get(i);
2107            BasePermission bp = mSettings.mPermissions.get(permission);
2108            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
2109                continue;
2110            }
2111            for (int userId : allUserIds) {
2112                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
2113                        permission, userId)) {
2114                    grantRuntimePermission(pkg.packageName, permission, userId);
2115                }
2116            }
2117        }
2118    }
2119
2120    private StorageEventListener mStorageListener = new StorageEventListener() {
2121        @Override
2122        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2123            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2124                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2125                    final String volumeUuid = vol.getFsUuid();
2126
2127                    // Clean up any users or apps that were removed or recreated
2128                    // while this volume was missing
2129                    sUserManager.reconcileUsers(volumeUuid);
2130                    reconcileApps(volumeUuid);
2131
2132                    // Clean up any install sessions that expired or were
2133                    // cancelled while this volume was missing
2134                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2135
2136                    loadPrivatePackages(vol);
2137
2138                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2139                    unloadPrivatePackages(vol);
2140                }
2141            }
2142
2143            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
2144                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2145                    updateExternalMediaStatus(true, false);
2146                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2147                    updateExternalMediaStatus(false, false);
2148                }
2149            }
2150        }
2151
2152        @Override
2153        public void onVolumeForgotten(String fsUuid) {
2154            if (TextUtils.isEmpty(fsUuid)) {
2155                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2156                return;
2157            }
2158
2159            // Remove any apps installed on the forgotten volume
2160            synchronized (mPackages) {
2161                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2162                for (PackageSetting ps : packages) {
2163                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2164                    deletePackageVersioned(new VersionedPackage(ps.name,
2165                            PackageManager.VERSION_CODE_HIGHEST),
2166                            new LegacyPackageDeleteObserver(null).getBinder(),
2167                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2168                    // Try very hard to release any references to this package
2169                    // so we don't risk the system server being killed due to
2170                    // open FDs
2171                    AttributeCache.instance().removePackage(ps.name);
2172                }
2173
2174                mSettings.onVolumeForgotten(fsUuid);
2175                mSettings.writeLPr();
2176            }
2177        }
2178    };
2179
2180    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2181            String[] grantedPermissions) {
2182        for (int userId : userIds) {
2183            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2184        }
2185    }
2186
2187    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2188            String[] grantedPermissions) {
2189        PackageSetting ps = (PackageSetting) pkg.mExtras;
2190        if (ps == null) {
2191            return;
2192        }
2193
2194        PermissionsState permissionsState = ps.getPermissionsState();
2195
2196        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2197                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2198
2199        final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
2200                >= Build.VERSION_CODES.M;
2201
2202        final boolean instantApp = isInstantApp(pkg.packageName, userId);
2203
2204        for (String permission : pkg.requestedPermissions) {
2205            final BasePermission bp;
2206            synchronized (mPackages) {
2207                bp = mSettings.mPermissions.get(permission);
2208            }
2209            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2210                    && (!instantApp || bp.isInstant())
2211                    && (supportsRuntimePermissions || !bp.isRuntimeOnly())
2212                    && (grantedPermissions == null
2213                           || ArrayUtils.contains(grantedPermissions, permission))) {
2214                final int flags = permissionsState.getPermissionFlags(permission, userId);
2215                if (supportsRuntimePermissions) {
2216                    // Installer cannot change immutable permissions.
2217                    if ((flags & immutableFlags) == 0) {
2218                        grantRuntimePermission(pkg.packageName, permission, userId);
2219                    }
2220                } else if (mPermissionReviewRequired) {
2221                    // In permission review mode we clear the review flag when we
2222                    // are asked to install the app with all permissions granted.
2223                    if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
2224                        updatePermissionFlags(permission, pkg.packageName,
2225                                PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId);
2226                    }
2227                }
2228            }
2229        }
2230    }
2231
2232    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2233        Bundle extras = null;
2234        switch (res.returnCode) {
2235            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2236                extras = new Bundle();
2237                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2238                        res.origPermission);
2239                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2240                        res.origPackage);
2241                break;
2242            }
2243            case PackageManager.INSTALL_SUCCEEDED: {
2244                extras = new Bundle();
2245                extras.putBoolean(Intent.EXTRA_REPLACING,
2246                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2247                break;
2248            }
2249        }
2250        return extras;
2251    }
2252
2253    void scheduleWriteSettingsLocked() {
2254        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2255            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2256        }
2257    }
2258
2259    void scheduleWritePackageListLocked(int userId) {
2260        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2261            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2262            msg.arg1 = userId;
2263            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2264        }
2265    }
2266
2267    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2268        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2269        scheduleWritePackageRestrictionsLocked(userId);
2270    }
2271
2272    void scheduleWritePackageRestrictionsLocked(int userId) {
2273        final int[] userIds = (userId == UserHandle.USER_ALL)
2274                ? sUserManager.getUserIds() : new int[]{userId};
2275        for (int nextUserId : userIds) {
2276            if (!sUserManager.exists(nextUserId)) return;
2277            mDirtyUsers.add(nextUserId);
2278            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2279                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2280            }
2281        }
2282    }
2283
2284    public static PackageManagerService main(Context context, Installer installer,
2285            boolean factoryTest, boolean onlyCore) {
2286        // Self-check for initial settings.
2287        PackageManagerServiceCompilerMapping.checkProperties();
2288
2289        PackageManagerService m = new PackageManagerService(context, installer,
2290                factoryTest, onlyCore);
2291        m.enableSystemUserPackages();
2292        ServiceManager.addService("package", m);
2293        return m;
2294    }
2295
2296    private void enableSystemUserPackages() {
2297        if (!UserManager.isSplitSystemUser()) {
2298            return;
2299        }
2300        // For system user, enable apps based on the following conditions:
2301        // - app is whitelisted or belong to one of these groups:
2302        //   -- system app which has no launcher icons
2303        //   -- system app which has INTERACT_ACROSS_USERS permission
2304        //   -- system IME app
2305        // - app is not in the blacklist
2306        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2307        Set<String> enableApps = new ArraySet<>();
2308        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2309                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2310                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2311        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2312        enableApps.addAll(wlApps);
2313        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2314                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2315        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2316        enableApps.removeAll(blApps);
2317        Log.i(TAG, "Applications installed for system user: " + enableApps);
2318        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2319                UserHandle.SYSTEM);
2320        final int allAppsSize = allAps.size();
2321        synchronized (mPackages) {
2322            for (int i = 0; i < allAppsSize; i++) {
2323                String pName = allAps.get(i);
2324                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2325                // Should not happen, but we shouldn't be failing if it does
2326                if (pkgSetting == null) {
2327                    continue;
2328                }
2329                boolean install = enableApps.contains(pName);
2330                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2331                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2332                            + " for system user");
2333                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2334                }
2335            }
2336            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2337        }
2338    }
2339
2340    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2341        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2342                Context.DISPLAY_SERVICE);
2343        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2344    }
2345
2346    /**
2347     * Requests that files preopted on a secondary system partition be copied to the data partition
2348     * if possible.  Note that the actual copying of the files is accomplished by init for security
2349     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2350     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2351     */
2352    private static void requestCopyPreoptedFiles() {
2353        final int WAIT_TIME_MS = 100;
2354        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2355        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2356            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2357            // We will wait for up to 100 seconds.
2358            final long timeStart = SystemClock.uptimeMillis();
2359            final long timeEnd = timeStart + 100 * 1000;
2360            long timeNow = timeStart;
2361            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2362                try {
2363                    Thread.sleep(WAIT_TIME_MS);
2364                } catch (InterruptedException e) {
2365                    // Do nothing
2366                }
2367                timeNow = SystemClock.uptimeMillis();
2368                if (timeNow > timeEnd) {
2369                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2370                    Slog.wtf(TAG, "cppreopt did not finish!");
2371                    break;
2372                }
2373            }
2374
2375            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2376        }
2377    }
2378
2379    public PackageManagerService(Context context, Installer installer,
2380            boolean factoryTest, boolean onlyCore) {
2381        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2382        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2383        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2384                SystemClock.uptimeMillis());
2385
2386        if (mSdkVersion <= 0) {
2387            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2388        }
2389
2390        mContext = context;
2391
2392        mPermissionReviewRequired = context.getResources().getBoolean(
2393                R.bool.config_permissionReviewRequired);
2394
2395        mFactoryTest = factoryTest;
2396        mOnlyCore = onlyCore;
2397        mMetrics = new DisplayMetrics();
2398        mSettings = new Settings(mPackages);
2399        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2400                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2401        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2402                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2403        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2404                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2405        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2406                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2407        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2408                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2409        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2410                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2411
2412        String separateProcesses = SystemProperties.get("debug.separate_processes");
2413        if (separateProcesses != null && separateProcesses.length() > 0) {
2414            if ("*".equals(separateProcesses)) {
2415                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2416                mSeparateProcesses = null;
2417                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2418            } else {
2419                mDefParseFlags = 0;
2420                mSeparateProcesses = separateProcesses.split(",");
2421                Slog.w(TAG, "Running with debug.separate_processes: "
2422                        + separateProcesses);
2423            }
2424        } else {
2425            mDefParseFlags = 0;
2426            mSeparateProcesses = null;
2427        }
2428
2429        mInstaller = installer;
2430        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2431                "*dexopt*");
2432        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
2433        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2434
2435        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2436                FgThread.get().getLooper());
2437
2438        getDefaultDisplayMetrics(context, mMetrics);
2439
2440        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2441        SystemConfig systemConfig = SystemConfig.getInstance();
2442        mGlobalGids = systemConfig.getGlobalGids();
2443        mSystemPermissions = systemConfig.getSystemPermissions();
2444        mAvailableFeatures = systemConfig.getAvailableFeatures();
2445        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2446
2447        mProtectedPackages = new ProtectedPackages(mContext);
2448
2449        synchronized (mInstallLock) {
2450        // writer
2451        synchronized (mPackages) {
2452            mHandlerThread = new ServiceThread(TAG,
2453                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2454            mHandlerThread.start();
2455            mHandler = new PackageHandler(mHandlerThread.getLooper());
2456            mProcessLoggingHandler = new ProcessLoggingHandler();
2457            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2458
2459            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2460            mInstantAppRegistry = new InstantAppRegistry(this);
2461
2462            File dataDir = Environment.getDataDirectory();
2463            mAppInstallDir = new File(dataDir, "app");
2464            mAppLib32InstallDir = new File(dataDir, "app-lib");
2465            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2466            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2467            sUserManager = new UserManagerService(context, this,
2468                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2469
2470            // Propagate permission configuration in to package manager.
2471            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2472                    = systemConfig.getPermissions();
2473            for (int i=0; i<permConfig.size(); i++) {
2474                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2475                BasePermission bp = mSettings.mPermissions.get(perm.name);
2476                if (bp == null) {
2477                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2478                    mSettings.mPermissions.put(perm.name, bp);
2479                }
2480                if (perm.gids != null) {
2481                    bp.setGids(perm.gids, perm.perUser);
2482                }
2483            }
2484
2485            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2486            final int builtInLibCount = libConfig.size();
2487            for (int i = 0; i < builtInLibCount; i++) {
2488                String name = libConfig.keyAt(i);
2489                String path = libConfig.valueAt(i);
2490                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2491                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2492            }
2493
2494            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2495
2496            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2497            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2498            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2499
2500            // Clean up orphaned packages for which the code path doesn't exist
2501            // and they are an update to a system app - caused by bug/32321269
2502            final int packageSettingCount = mSettings.mPackages.size();
2503            for (int i = packageSettingCount - 1; i >= 0; i--) {
2504                PackageSetting ps = mSettings.mPackages.valueAt(i);
2505                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2506                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2507                    mSettings.mPackages.removeAt(i);
2508                    mSettings.enableSystemPackageLPw(ps.name);
2509                }
2510            }
2511
2512            if (mFirstBoot) {
2513                requestCopyPreoptedFiles();
2514            }
2515
2516            String customResolverActivity = Resources.getSystem().getString(
2517                    R.string.config_customResolverActivity);
2518            if (TextUtils.isEmpty(customResolverActivity)) {
2519                customResolverActivity = null;
2520            } else {
2521                mCustomResolverComponentName = ComponentName.unflattenFromString(
2522                        customResolverActivity);
2523            }
2524
2525            long startTime = SystemClock.uptimeMillis();
2526
2527            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2528                    startTime);
2529
2530            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2531            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2532
2533            if (bootClassPath == null) {
2534                Slog.w(TAG, "No BOOTCLASSPATH found!");
2535            }
2536
2537            if (systemServerClassPath == null) {
2538                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2539            }
2540
2541            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2542
2543            final VersionInfo ver = mSettings.getInternalVersion();
2544            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2545            if (mIsUpgrade) {
2546                logCriticalInfo(Log.INFO,
2547                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2548            }
2549
2550            // when upgrading from pre-M, promote system app permissions from install to runtime
2551            mPromoteSystemApps =
2552                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2553
2554            // When upgrading from pre-N, we need to handle package extraction like first boot,
2555            // as there is no profiling data available.
2556            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2557
2558            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2559
2560            // save off the names of pre-existing system packages prior to scanning; we don't
2561            // want to automatically grant runtime permissions for new system apps
2562            if (mPromoteSystemApps) {
2563                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2564                while (pkgSettingIter.hasNext()) {
2565                    PackageSetting ps = pkgSettingIter.next();
2566                    if (isSystemApp(ps)) {
2567                        mExistingSystemPackages.add(ps.name);
2568                    }
2569                }
2570            }
2571
2572            mCacheDir = preparePackageParserCache(mIsUpgrade);
2573
2574            // Set flag to monitor and not change apk file paths when
2575            // scanning install directories.
2576            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2577
2578            if (mIsUpgrade || mFirstBoot) {
2579                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2580            }
2581
2582            // Collect vendor overlay packages. (Do this before scanning any apps.)
2583            // For security and version matching reason, only consider
2584            // overlay packages if they reside in the right directory.
2585            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2586                    | PackageParser.PARSE_IS_SYSTEM
2587                    | PackageParser.PARSE_IS_SYSTEM_DIR
2588                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2589
2590            mParallelPackageParserCallback.findStaticOverlayPackages();
2591
2592            // Find base frameworks (resource packages without code).
2593            scanDirTracedLI(frameworkDir, mDefParseFlags
2594                    | PackageParser.PARSE_IS_SYSTEM
2595                    | PackageParser.PARSE_IS_SYSTEM_DIR
2596                    | PackageParser.PARSE_IS_PRIVILEGED,
2597                    scanFlags | SCAN_NO_DEX, 0);
2598
2599            // Collected privileged system packages.
2600            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2601            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2602                    | PackageParser.PARSE_IS_SYSTEM
2603                    | PackageParser.PARSE_IS_SYSTEM_DIR
2604                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2605
2606            // Collect ordinary system packages.
2607            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2608            scanDirTracedLI(systemAppDir, mDefParseFlags
2609                    | PackageParser.PARSE_IS_SYSTEM
2610                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2611
2612            // Collect all vendor packages.
2613            File vendorAppDir = new File("/vendor/app");
2614            try {
2615                vendorAppDir = vendorAppDir.getCanonicalFile();
2616            } catch (IOException e) {
2617                // failed to look up canonical path, continue with original one
2618            }
2619            scanDirTracedLI(vendorAppDir, mDefParseFlags
2620                    | PackageParser.PARSE_IS_SYSTEM
2621                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2622
2623            // Collect all OEM packages.
2624            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2625            scanDirTracedLI(oemAppDir, mDefParseFlags
2626                    | PackageParser.PARSE_IS_SYSTEM
2627                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2628
2629            // Prune any system packages that no longer exist.
2630            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2631            if (!mOnlyCore) {
2632                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2633                while (psit.hasNext()) {
2634                    PackageSetting ps = psit.next();
2635
2636                    /*
2637                     * If this is not a system app, it can't be a
2638                     * disable system app.
2639                     */
2640                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2641                        continue;
2642                    }
2643
2644                    /*
2645                     * If the package is scanned, it's not erased.
2646                     */
2647                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2648                    if (scannedPkg != null) {
2649                        /*
2650                         * If the system app is both scanned and in the
2651                         * disabled packages list, then it must have been
2652                         * added via OTA. Remove it from the currently
2653                         * scanned package so the previously user-installed
2654                         * application can be scanned.
2655                         */
2656                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2657                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2658                                    + ps.name + "; removing system app.  Last known codePath="
2659                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2660                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2661                                    + scannedPkg.mVersionCode);
2662                            removePackageLI(scannedPkg, true);
2663                            mExpectingBetter.put(ps.name, ps.codePath);
2664                        }
2665
2666                        continue;
2667                    }
2668
2669                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2670                        psit.remove();
2671                        logCriticalInfo(Log.WARN, "System package " + ps.name
2672                                + " no longer exists; it's data will be wiped");
2673                        // Actual deletion of code and data will be handled by later
2674                        // reconciliation step
2675                    } else {
2676                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2677                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2678                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2679                        }
2680                    }
2681                }
2682            }
2683
2684            //look for any incomplete package installations
2685            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2686            for (int i = 0; i < deletePkgsList.size(); i++) {
2687                // Actual deletion of code and data will be handled by later
2688                // reconciliation step
2689                final String packageName = deletePkgsList.get(i).name;
2690                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2691                synchronized (mPackages) {
2692                    mSettings.removePackageLPw(packageName);
2693                }
2694            }
2695
2696            //delete tmp files
2697            deleteTempPackageFiles();
2698
2699            // Remove any shared userIDs that have no associated packages
2700            mSettings.pruneSharedUsersLPw();
2701
2702            if (!mOnlyCore) {
2703                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2704                        SystemClock.uptimeMillis());
2705                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2706
2707                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2708                        | PackageParser.PARSE_FORWARD_LOCK,
2709                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2710
2711                /**
2712                 * Remove disable package settings for any updated system
2713                 * apps that were removed via an OTA. If they're not a
2714                 * previously-updated app, remove them completely.
2715                 * Otherwise, just revoke their system-level permissions.
2716                 */
2717                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2718                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2719                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2720
2721                    String msg;
2722                    if (deletedPkg == null) {
2723                        msg = "Updated system package " + deletedAppName
2724                                + " no longer exists; it's data will be wiped";
2725                        // Actual deletion of code and data will be handled by later
2726                        // reconciliation step
2727                    } else {
2728                        msg = "Updated system app + " + deletedAppName
2729                                + " no longer present; removing system privileges for "
2730                                + deletedAppName;
2731
2732                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2733
2734                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2735                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2736                    }
2737                    logCriticalInfo(Log.WARN, msg);
2738                }
2739
2740                /**
2741                 * Make sure all system apps that we expected to appear on
2742                 * the userdata partition actually showed up. If they never
2743                 * appeared, crawl back and revive the system version.
2744                 */
2745                for (int i = 0; i < mExpectingBetter.size(); i++) {
2746                    final String packageName = mExpectingBetter.keyAt(i);
2747                    if (!mPackages.containsKey(packageName)) {
2748                        final File scanFile = mExpectingBetter.valueAt(i);
2749
2750                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2751                                + " but never showed up; reverting to system");
2752
2753                        int reparseFlags = mDefParseFlags;
2754                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2755                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2756                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2757                                    | PackageParser.PARSE_IS_PRIVILEGED;
2758                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2759                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2760                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2761                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2762                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2763                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2764                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2765                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2766                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2767                        } else {
2768                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2769                            continue;
2770                        }
2771
2772                        mSettings.enableSystemPackageLPw(packageName);
2773
2774                        try {
2775                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2776                        } catch (PackageManagerException e) {
2777                            Slog.e(TAG, "Failed to parse original system package: "
2778                                    + e.getMessage());
2779                        }
2780                    }
2781                }
2782            }
2783            mExpectingBetter.clear();
2784
2785            // Resolve the storage manager.
2786            mStorageManagerPackage = getStorageManagerPackageName();
2787
2788            // Resolve protected action filters. Only the setup wizard is allowed to
2789            // have a high priority filter for these actions.
2790            mSetupWizardPackage = getSetupWizardPackageName();
2791            if (mProtectedFilters.size() > 0) {
2792                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2793                    Slog.i(TAG, "No setup wizard;"
2794                        + " All protected intents capped to priority 0");
2795                }
2796                for (ActivityIntentInfo filter : mProtectedFilters) {
2797                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2798                        if (DEBUG_FILTERS) {
2799                            Slog.i(TAG, "Found setup wizard;"
2800                                + " allow priority " + filter.getPriority() + ";"
2801                                + " package: " + filter.activity.info.packageName
2802                                + " activity: " + filter.activity.className
2803                                + " priority: " + filter.getPriority());
2804                        }
2805                        // skip setup wizard; allow it to keep the high priority filter
2806                        continue;
2807                    }
2808                    if (DEBUG_FILTERS) {
2809                        Slog.i(TAG, "Protected action; cap priority to 0;"
2810                                + " package: " + filter.activity.info.packageName
2811                                + " activity: " + filter.activity.className
2812                                + " origPrio: " + filter.getPriority());
2813                    }
2814                    filter.setPriority(0);
2815                }
2816            }
2817            mDeferProtectedFilters = false;
2818            mProtectedFilters.clear();
2819
2820            // Now that we know all of the shared libraries, update all clients to have
2821            // the correct library paths.
2822            updateAllSharedLibrariesLPw(null);
2823
2824            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2825                // NOTE: We ignore potential failures here during a system scan (like
2826                // the rest of the commands above) because there's precious little we
2827                // can do about it. A settings error is reported, though.
2828                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2829            }
2830
2831            // Now that we know all the packages we are keeping,
2832            // read and update their last usage times.
2833            mPackageUsage.read(mPackages);
2834            mCompilerStats.read();
2835
2836            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2837                    SystemClock.uptimeMillis());
2838            Slog.i(TAG, "Time to scan packages: "
2839                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2840                    + " seconds");
2841
2842            // If the platform SDK has changed since the last time we booted,
2843            // we need to re-grant app permission to catch any new ones that
2844            // appear.  This is really a hack, and means that apps can in some
2845            // cases get permissions that the user didn't initially explicitly
2846            // allow...  it would be nice to have some better way to handle
2847            // this situation.
2848            int updateFlags = UPDATE_PERMISSIONS_ALL;
2849            if (ver.sdkVersion != mSdkVersion) {
2850                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2851                        + mSdkVersion + "; regranting permissions for internal storage");
2852                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2853            }
2854            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2855            ver.sdkVersion = mSdkVersion;
2856
2857            // If this is the first boot or an update from pre-M, and it is a normal
2858            // boot, then we need to initialize the default preferred apps across
2859            // all defined users.
2860            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2861                for (UserInfo user : sUserManager.getUsers(true)) {
2862                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2863                    applyFactoryDefaultBrowserLPw(user.id);
2864                    primeDomainVerificationsLPw(user.id);
2865                }
2866            }
2867
2868            // Prepare storage for system user really early during boot,
2869            // since core system apps like SettingsProvider and SystemUI
2870            // can't wait for user to start
2871            final int storageFlags;
2872            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2873                storageFlags = StorageManager.FLAG_STORAGE_DE;
2874            } else {
2875                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2876            }
2877            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2878                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2879                    true /* onlyCoreApps */);
2880            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2881                BootTimingsTraceLog traceLog = new BootTimingsTraceLog("SystemServerTimingAsync",
2882                        Trace.TRACE_TAG_PACKAGE_MANAGER);
2883                traceLog.traceBegin("AppDataFixup");
2884                try {
2885                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
2886                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2887                } catch (InstallerException e) {
2888                    Slog.w(TAG, "Trouble fixing GIDs", e);
2889                }
2890                traceLog.traceEnd();
2891
2892                traceLog.traceBegin("AppDataPrepare");
2893                if (deferPackages == null || deferPackages.isEmpty()) {
2894                    return;
2895                }
2896                int count = 0;
2897                for (String pkgName : deferPackages) {
2898                    PackageParser.Package pkg = null;
2899                    synchronized (mPackages) {
2900                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
2901                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
2902                            pkg = ps.pkg;
2903                        }
2904                    }
2905                    if (pkg != null) {
2906                        synchronized (mInstallLock) {
2907                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
2908                                    true /* maybeMigrateAppData */);
2909                        }
2910                        count++;
2911                    }
2912                }
2913                traceLog.traceEnd();
2914                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
2915            }, "prepareAppData");
2916
2917            // If this is first boot after an OTA, and a normal boot, then
2918            // we need to clear code cache directories.
2919            // Note that we do *not* clear the application profiles. These remain valid
2920            // across OTAs and are used to drive profile verification (post OTA) and
2921            // profile compilation (without waiting to collect a fresh set of profiles).
2922            if (mIsUpgrade && !onlyCore) {
2923                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2924                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2925                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2926                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2927                        // No apps are running this early, so no need to freeze
2928                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2929                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2930                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2931                    }
2932                }
2933                ver.fingerprint = Build.FINGERPRINT;
2934            }
2935
2936            checkDefaultBrowser();
2937
2938            // clear only after permissions and other defaults have been updated
2939            mExistingSystemPackages.clear();
2940            mPromoteSystemApps = false;
2941
2942            // All the changes are done during package scanning.
2943            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2944
2945            // can downgrade to reader
2946            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
2947            mSettings.writeLPr();
2948            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2949            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2950                    SystemClock.uptimeMillis());
2951
2952            if (!mOnlyCore) {
2953                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2954                mRequiredInstallerPackage = getRequiredInstallerLPr();
2955                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2956                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2957                if (mIntentFilterVerifierComponent != null) {
2958                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2959                            mIntentFilterVerifierComponent);
2960                } else {
2961                    mIntentFilterVerifier = null;
2962                }
2963                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2964                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
2965                        SharedLibraryInfo.VERSION_UNDEFINED);
2966                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2967                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
2968                        SharedLibraryInfo.VERSION_UNDEFINED);
2969            } else {
2970                mRequiredVerifierPackage = null;
2971                mRequiredInstallerPackage = null;
2972                mRequiredUninstallerPackage = null;
2973                mIntentFilterVerifierComponent = null;
2974                mIntentFilterVerifier = null;
2975                mServicesSystemSharedLibraryPackageName = null;
2976                mSharedSystemSharedLibraryPackageName = null;
2977            }
2978
2979            mInstallerService = new PackageInstallerService(context, this);
2980            final Pair<ComponentName, String> instantAppResolverComponent =
2981                    getInstantAppResolverLPr();
2982            if (instantAppResolverComponent != null) {
2983                if (DEBUG_EPHEMERAL) {
2984                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
2985                }
2986                mInstantAppResolverConnection = new EphemeralResolverConnection(
2987                        mContext, instantAppResolverComponent.first,
2988                        instantAppResolverComponent.second);
2989                mInstantAppResolverSettingsComponent =
2990                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
2991            } else {
2992                mInstantAppResolverConnection = null;
2993                mInstantAppResolverSettingsComponent = null;
2994            }
2995            updateInstantAppInstallerLocked(null);
2996
2997            // Read and update the usage of dex files.
2998            // Do this at the end of PM init so that all the packages have their
2999            // data directory reconciled.
3000            // At this point we know the code paths of the packages, so we can validate
3001            // the disk file and build the internal cache.
3002            // The usage file is expected to be small so loading and verifying it
3003            // should take a fairly small time compare to the other activities (e.g. package
3004            // scanning).
3005            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3006            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3007            for (int userId : currentUserIds) {
3008                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3009            }
3010            mDexManager.load(userPackages);
3011        } // synchronized (mPackages)
3012        } // synchronized (mInstallLock)
3013
3014        // Now after opening every single application zip, make sure they
3015        // are all flushed.  Not really needed, but keeps things nice and
3016        // tidy.
3017        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3018        Runtime.getRuntime().gc();
3019        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3020
3021        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3022        FallbackCategoryProvider.loadFallbacks();
3023        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3024
3025        // The initial scanning above does many calls into installd while
3026        // holding the mPackages lock, but we're mostly interested in yelling
3027        // once we have a booted system.
3028        mInstaller.setWarnIfHeld(mPackages);
3029
3030        // Expose private service for system components to use.
3031        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
3032        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3033    }
3034
3035    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3036        // we're only interested in updating the installer appliction when 1) it's not
3037        // already set or 2) the modified package is the installer
3038        if (mInstantAppInstallerActivity != null
3039                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3040                        .equals(modifiedPackage)) {
3041            return;
3042        }
3043        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3044    }
3045
3046    private static File preparePackageParserCache(boolean isUpgrade) {
3047        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3048            return null;
3049        }
3050
3051        // Disable package parsing on eng builds to allow for faster incremental development.
3052        if ("eng".equals(Build.TYPE)) {
3053            return null;
3054        }
3055
3056        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3057            Slog.i(TAG, "Disabling package parser cache due to system property.");
3058            return null;
3059        }
3060
3061        // The base directory for the package parser cache lives under /data/system/.
3062        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3063                "package_cache");
3064        if (cacheBaseDir == null) {
3065            return null;
3066        }
3067
3068        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3069        // This also serves to "GC" unused entries when the package cache version changes (which
3070        // can only happen during upgrades).
3071        if (isUpgrade) {
3072            FileUtils.deleteContents(cacheBaseDir);
3073        }
3074
3075
3076        // Return the versioned package cache directory. This is something like
3077        // "/data/system/package_cache/1"
3078        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3079
3080        // The following is a workaround to aid development on non-numbered userdebug
3081        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3082        // the system partition is newer.
3083        //
3084        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3085        // that starts with "eng." to signify that this is an engineering build and not
3086        // destined for release.
3087        if ("userdebug".equals(Build.TYPE) && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3088            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3089
3090            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3091            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3092            // in general and should not be used for production changes. In this specific case,
3093            // we know that they will work.
3094            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3095            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3096                FileUtils.deleteContents(cacheBaseDir);
3097                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3098            }
3099        }
3100
3101        return cacheDir;
3102    }
3103
3104    @Override
3105    public boolean isFirstBoot() {
3106        // allow instant applications
3107        return mFirstBoot;
3108    }
3109
3110    @Override
3111    public boolean isOnlyCoreApps() {
3112        // allow instant applications
3113        return mOnlyCore;
3114    }
3115
3116    @Override
3117    public boolean isUpgrade() {
3118        // allow instant applications
3119        return mIsUpgrade;
3120    }
3121
3122    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3123        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3124
3125        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3126                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3127                UserHandle.USER_SYSTEM);
3128        if (matches.size() == 1) {
3129            return matches.get(0).getComponentInfo().packageName;
3130        } else if (matches.size() == 0) {
3131            Log.e(TAG, "There should probably be a verifier, but, none were found");
3132            return null;
3133        }
3134        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3135    }
3136
3137    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3138        synchronized (mPackages) {
3139            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3140            if (libraryEntry == null) {
3141                throw new IllegalStateException("Missing required shared library:" + name);
3142            }
3143            return libraryEntry.apk;
3144        }
3145    }
3146
3147    private @NonNull String getRequiredInstallerLPr() {
3148        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3149        intent.addCategory(Intent.CATEGORY_DEFAULT);
3150        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3151
3152        final List<ResolveInfo> matches = queryIntentActivitiesInternal(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            ResolveInfo resolveInfo = matches.get(0);
3157            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3158                throw new RuntimeException("The installer must be a privileged app");
3159            }
3160            return matches.get(0).getComponentInfo().packageName;
3161        } else {
3162            throw new RuntimeException("There must be exactly one installer; found " + matches);
3163        }
3164    }
3165
3166    private @NonNull String getRequiredUninstallerLPr() {
3167        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3168        intent.addCategory(Intent.CATEGORY_DEFAULT);
3169        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3170
3171        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3172                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3173                UserHandle.USER_SYSTEM);
3174        if (resolveInfo == null ||
3175                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3176            throw new RuntimeException("There must be exactly one uninstaller; found "
3177                    + resolveInfo);
3178        }
3179        return resolveInfo.getComponentInfo().packageName;
3180    }
3181
3182    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3183        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3184
3185        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3186                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3187                UserHandle.USER_SYSTEM);
3188        ResolveInfo best = null;
3189        final int N = matches.size();
3190        for (int i = 0; i < N; i++) {
3191            final ResolveInfo cur = matches.get(i);
3192            final String packageName = cur.getComponentInfo().packageName;
3193            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3194                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3195                continue;
3196            }
3197
3198            if (best == null || cur.priority > best.priority) {
3199                best = cur;
3200            }
3201        }
3202
3203        if (best != null) {
3204            return best.getComponentInfo().getComponentName();
3205        }
3206        Slog.w(TAG, "Intent filter verifier not found");
3207        return null;
3208    }
3209
3210    @Override
3211    public @Nullable ComponentName getInstantAppResolverComponent() {
3212        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3213            return null;
3214        }
3215        synchronized (mPackages) {
3216            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3217            if (instantAppResolver == null) {
3218                return null;
3219            }
3220            return instantAppResolver.first;
3221        }
3222    }
3223
3224    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3225        final String[] packageArray =
3226                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3227        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3228            if (DEBUG_EPHEMERAL) {
3229                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3230            }
3231            return null;
3232        }
3233
3234        final int callingUid = Binder.getCallingUid();
3235        final int resolveFlags =
3236                MATCH_DIRECT_BOOT_AWARE
3237                | MATCH_DIRECT_BOOT_UNAWARE
3238                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3239        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3240        final Intent resolverIntent = new Intent(actionName);
3241        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3242                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3243        // temporarily look for the old action
3244        if (resolvers.size() == 0) {
3245            if (DEBUG_EPHEMERAL) {
3246                Slog.d(TAG, "Ephemeral resolver not found with new action; try old one");
3247            }
3248            actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE;
3249            resolverIntent.setAction(actionName);
3250            resolvers = queryIntentServicesInternal(resolverIntent, null,
3251                    resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3252        }
3253        final int N = resolvers.size();
3254        if (N == 0) {
3255            if (DEBUG_EPHEMERAL) {
3256                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3257            }
3258            return null;
3259        }
3260
3261        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3262        for (int i = 0; i < N; i++) {
3263            final ResolveInfo info = resolvers.get(i);
3264
3265            if (info.serviceInfo == null) {
3266                continue;
3267            }
3268
3269            final String packageName = info.serviceInfo.packageName;
3270            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3271                if (DEBUG_EPHEMERAL) {
3272                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3273                            + " pkg: " + packageName + ", info:" + info);
3274                }
3275                continue;
3276            }
3277
3278            if (DEBUG_EPHEMERAL) {
3279                Slog.v(TAG, "Ephemeral resolver found;"
3280                        + " pkg: " + packageName + ", info:" + info);
3281            }
3282            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3283        }
3284        if (DEBUG_EPHEMERAL) {
3285            Slog.v(TAG, "Ephemeral resolver NOT found");
3286        }
3287        return null;
3288    }
3289
3290    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3291        final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE);
3292        intent.addCategory(Intent.CATEGORY_DEFAULT);
3293        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3294
3295        final int resolveFlags =
3296                MATCH_DIRECT_BOOT_AWARE
3297                | MATCH_DIRECT_BOOT_UNAWARE
3298                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3299        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3300                resolveFlags, UserHandle.USER_SYSTEM);
3301        // temporarily look for the old action
3302        if (matches.isEmpty()) {
3303            if (DEBUG_EPHEMERAL) {
3304                Slog.d(TAG, "Ephemeral installer not found with new action; try old one");
3305            }
3306            intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3307            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3308                    resolveFlags, UserHandle.USER_SYSTEM);
3309        }
3310        Iterator<ResolveInfo> iter = matches.iterator();
3311        while (iter.hasNext()) {
3312            final ResolveInfo rInfo = iter.next();
3313            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3314            if (ps != null) {
3315                final PermissionsState permissionsState = ps.getPermissionsState();
3316                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3317                    continue;
3318                }
3319            }
3320            iter.remove();
3321        }
3322        if (matches.size() == 0) {
3323            return null;
3324        } else if (matches.size() == 1) {
3325            return (ActivityInfo) matches.get(0).getComponentInfo();
3326        } else {
3327            throw new RuntimeException(
3328                    "There must be at most one ephemeral installer; found " + matches);
3329        }
3330    }
3331
3332    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3333            @NonNull ComponentName resolver) {
3334        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3335                .addCategory(Intent.CATEGORY_DEFAULT)
3336                .setPackage(resolver.getPackageName());
3337        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3338        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3339                UserHandle.USER_SYSTEM);
3340        // temporarily look for the old action
3341        if (matches.isEmpty()) {
3342            if (DEBUG_EPHEMERAL) {
3343                Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one");
3344            }
3345            intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS);
3346            matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3347                    UserHandle.USER_SYSTEM);
3348        }
3349        if (matches.isEmpty()) {
3350            return null;
3351        }
3352        return matches.get(0).getComponentInfo().getComponentName();
3353    }
3354
3355    private void primeDomainVerificationsLPw(int userId) {
3356        if (DEBUG_DOMAIN_VERIFICATION) {
3357            Slog.d(TAG, "Priming domain verifications in user " + userId);
3358        }
3359
3360        SystemConfig systemConfig = SystemConfig.getInstance();
3361        ArraySet<String> packages = systemConfig.getLinkedApps();
3362
3363        for (String packageName : packages) {
3364            PackageParser.Package pkg = mPackages.get(packageName);
3365            if (pkg != null) {
3366                if (!pkg.isSystemApp()) {
3367                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3368                    continue;
3369                }
3370
3371                ArraySet<String> domains = null;
3372                for (PackageParser.Activity a : pkg.activities) {
3373                    for (ActivityIntentInfo filter : a.intents) {
3374                        if (hasValidDomains(filter)) {
3375                            if (domains == null) {
3376                                domains = new ArraySet<String>();
3377                            }
3378                            domains.addAll(filter.getHostsList());
3379                        }
3380                    }
3381                }
3382
3383                if (domains != null && domains.size() > 0) {
3384                    if (DEBUG_DOMAIN_VERIFICATION) {
3385                        Slog.v(TAG, "      + " + packageName);
3386                    }
3387                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3388                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3389                    // and then 'always' in the per-user state actually used for intent resolution.
3390                    final IntentFilterVerificationInfo ivi;
3391                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3392                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3393                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3394                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3395                } else {
3396                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3397                            + "' does not handle web links");
3398                }
3399            } else {
3400                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3401            }
3402        }
3403
3404        scheduleWritePackageRestrictionsLocked(userId);
3405        scheduleWriteSettingsLocked();
3406    }
3407
3408    private void applyFactoryDefaultBrowserLPw(int userId) {
3409        // The default browser app's package name is stored in a string resource,
3410        // with a product-specific overlay used for vendor customization.
3411        String browserPkg = mContext.getResources().getString(
3412                com.android.internal.R.string.default_browser);
3413        if (!TextUtils.isEmpty(browserPkg)) {
3414            // non-empty string => required to be a known package
3415            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3416            if (ps == null) {
3417                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3418                browserPkg = null;
3419            } else {
3420                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3421            }
3422        }
3423
3424        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3425        // default.  If there's more than one, just leave everything alone.
3426        if (browserPkg == null) {
3427            calculateDefaultBrowserLPw(userId);
3428        }
3429    }
3430
3431    private void calculateDefaultBrowserLPw(int userId) {
3432        List<String> allBrowsers = resolveAllBrowserApps(userId);
3433        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3434        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3435    }
3436
3437    private List<String> resolveAllBrowserApps(int userId) {
3438        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3439        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3440                PackageManager.MATCH_ALL, userId);
3441
3442        final int count = list.size();
3443        List<String> result = new ArrayList<String>(count);
3444        for (int i=0; i<count; i++) {
3445            ResolveInfo info = list.get(i);
3446            if (info.activityInfo == null
3447                    || !info.handleAllWebDataURI
3448                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3449                    || result.contains(info.activityInfo.packageName)) {
3450                continue;
3451            }
3452            result.add(info.activityInfo.packageName);
3453        }
3454
3455        return result;
3456    }
3457
3458    private boolean packageIsBrowser(String packageName, int userId) {
3459        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3460                PackageManager.MATCH_ALL, userId);
3461        final int N = list.size();
3462        for (int i = 0; i < N; i++) {
3463            ResolveInfo info = list.get(i);
3464            if (packageName.equals(info.activityInfo.packageName)) {
3465                return true;
3466            }
3467        }
3468        return false;
3469    }
3470
3471    private void checkDefaultBrowser() {
3472        final int myUserId = UserHandle.myUserId();
3473        final String packageName = getDefaultBrowserPackageName(myUserId);
3474        if (packageName != null) {
3475            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3476            if (info == null) {
3477                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3478                synchronized (mPackages) {
3479                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3480                }
3481            }
3482        }
3483    }
3484
3485    @Override
3486    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3487            throws RemoteException {
3488        try {
3489            return super.onTransact(code, data, reply, flags);
3490        } catch (RuntimeException e) {
3491            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3492                Slog.wtf(TAG, "Package Manager Crash", e);
3493            }
3494            throw e;
3495        }
3496    }
3497
3498    static int[] appendInts(int[] cur, int[] add) {
3499        if (add == null) return cur;
3500        if (cur == null) return add;
3501        final int N = add.length;
3502        for (int i=0; i<N; i++) {
3503            cur = appendInt(cur, add[i]);
3504        }
3505        return cur;
3506    }
3507
3508    /**
3509     * Returns whether or not a full application can see an instant application.
3510     * <p>
3511     * Currently, there are three cases in which this can occur:
3512     * <ol>
3513     * <li>The calling application is a "special" process. The special
3514     *     processes are {@link Process#SYSTEM_UID}, {@link Process#SHELL_UID}
3515     *     and {@code 0}</li>
3516     * <li>The calling application has the permission
3517     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}</li>
3518     * <li>The calling application is the default launcher on the
3519     *     system partition.</li>
3520     * </ol>
3521     */
3522    private boolean canViewInstantApps(int callingUid, int userId) {
3523        if (callingUid == Process.SYSTEM_UID
3524                || callingUid == Process.SHELL_UID
3525                || callingUid == Process.ROOT_UID) {
3526            return true;
3527        }
3528        if (mContext.checkCallingOrSelfPermission(
3529                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3530            return true;
3531        }
3532        if (mContext.checkCallingOrSelfPermission(
3533                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3534            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3535            if (homeComponent != null
3536                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3537                return true;
3538            }
3539        }
3540        return false;
3541    }
3542
3543    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3544        if (!sUserManager.exists(userId)) return null;
3545        if (ps == null) {
3546            return null;
3547        }
3548        PackageParser.Package p = ps.pkg;
3549        if (p == null) {
3550            return null;
3551        }
3552        final int callingUid = Binder.getCallingUid();
3553        // Filter out ephemeral app metadata:
3554        //   * The system/shell/root can see metadata for any app
3555        //   * An installed app can see metadata for 1) other installed apps
3556        //     and 2) ephemeral apps that have explicitly interacted with it
3557        //   * Ephemeral apps can only see their own data and exposed installed apps
3558        //   * Holding a signature permission allows seeing instant apps
3559        if (filterAppAccessLPr(ps, callingUid, userId)) {
3560            return null;
3561        }
3562
3563        final PermissionsState permissionsState = ps.getPermissionsState();
3564
3565        // Compute GIDs only if requested
3566        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3567                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3568        // Compute granted permissions only if package has requested permissions
3569        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3570                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3571        final PackageUserState state = ps.readUserState(userId);
3572
3573        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3574                && ps.isSystem()) {
3575            flags |= MATCH_ANY_USER;
3576        }
3577
3578        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3579                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3580
3581        if (packageInfo == null) {
3582            return null;
3583        }
3584
3585        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3586                resolveExternalPackageNameLPr(p);
3587
3588        return packageInfo;
3589    }
3590
3591    @Override
3592    public void checkPackageStartable(String packageName, int userId) {
3593        final int callingUid = Binder.getCallingUid();
3594        if (getInstantAppPackageName(callingUid) != null) {
3595            throw new SecurityException("Instant applications don't have access to this method");
3596        }
3597        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3598        synchronized (mPackages) {
3599            final PackageSetting ps = mSettings.mPackages.get(packageName);
3600            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3601                throw new SecurityException("Package " + packageName + " was not found!");
3602            }
3603
3604            if (!ps.getInstalled(userId)) {
3605                throw new SecurityException(
3606                        "Package " + packageName + " was not installed for user " + userId + "!");
3607            }
3608
3609            if (mSafeMode && !ps.isSystem()) {
3610                throw new SecurityException("Package " + packageName + " not a system app!");
3611            }
3612
3613            if (mFrozenPackages.contains(packageName)) {
3614                throw new SecurityException("Package " + packageName + " is currently frozen!");
3615            }
3616
3617            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3618                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3619                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3620            }
3621        }
3622    }
3623
3624    @Override
3625    public boolean isPackageAvailable(String packageName, int userId) {
3626        if (!sUserManager.exists(userId)) return false;
3627        final int callingUid = Binder.getCallingUid();
3628        enforceCrossUserPermission(callingUid, userId,
3629                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
3630        synchronized (mPackages) {
3631            PackageParser.Package p = mPackages.get(packageName);
3632            if (p != null) {
3633                final PackageSetting ps = (PackageSetting) p.mExtras;
3634                if (filterAppAccessLPr(ps, callingUid, userId)) {
3635                    return false;
3636                }
3637                if (ps != null) {
3638                    final PackageUserState state = ps.readUserState(userId);
3639                    if (state != null) {
3640                        return PackageParser.isAvailable(state);
3641                    }
3642                }
3643            }
3644        }
3645        return false;
3646    }
3647
3648    @Override
3649    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3650        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3651                flags, Binder.getCallingUid(), userId);
3652    }
3653
3654    @Override
3655    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3656            int flags, int userId) {
3657        return getPackageInfoInternal(versionedPackage.getPackageName(),
3658                versionedPackage.getVersionCode(), flags, Binder.getCallingUid(), userId);
3659    }
3660
3661    /**
3662     * Important: The provided filterCallingUid is used exclusively to filter out packages
3663     * that can be seen based on user state. It's typically the original caller uid prior
3664     * to clearing. Because it can only be provided by trusted code, it's value can be
3665     * trusted and will be used as-is; unlike userId which will be validated by this method.
3666     */
3667    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3668            int flags, int filterCallingUid, int userId) {
3669        if (!sUserManager.exists(userId)) return null;
3670        flags = updateFlagsForPackage(flags, userId, packageName);
3671        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3672                false /* requireFullPermission */, false /* checkShell */, "get package info");
3673
3674        // reader
3675        synchronized (mPackages) {
3676            // Normalize package name to handle renamed packages and static libs
3677            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3678
3679            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3680            if (matchFactoryOnly) {
3681                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3682                if (ps != null) {
3683                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3684                        return null;
3685                    }
3686                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3687                        return null;
3688                    }
3689                    return generatePackageInfo(ps, flags, userId);
3690                }
3691            }
3692
3693            PackageParser.Package p = mPackages.get(packageName);
3694            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3695                return null;
3696            }
3697            if (DEBUG_PACKAGE_INFO)
3698                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3699            if (p != null) {
3700                final PackageSetting ps = (PackageSetting) p.mExtras;
3701                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3702                    return null;
3703                }
3704                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
3705                    return null;
3706                }
3707                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3708            }
3709            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3710                final PackageSetting ps = mSettings.mPackages.get(packageName);
3711                if (ps == null) return null;
3712                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3713                    return null;
3714                }
3715                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3716                    return null;
3717                }
3718                return generatePackageInfo(ps, flags, userId);
3719            }
3720        }
3721        return null;
3722    }
3723
3724    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
3725        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
3726            return true;
3727        }
3728        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
3729            return true;
3730        }
3731        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
3732            return true;
3733        }
3734        return false;
3735    }
3736
3737    private boolean isComponentVisibleToInstantApp(
3738            @Nullable ComponentName component, @ComponentType int type) {
3739        if (type == TYPE_ACTIVITY) {
3740            final PackageParser.Activity activity = mActivities.mActivities.get(component);
3741            return activity != null
3742                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3743                    : false;
3744        } else if (type == TYPE_RECEIVER) {
3745            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
3746            return activity != null
3747                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3748                    : false;
3749        } else if (type == TYPE_SERVICE) {
3750            final PackageParser.Service service = mServices.mServices.get(component);
3751            return service != null
3752                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3753                    : false;
3754        } else if (type == TYPE_PROVIDER) {
3755            final PackageParser.Provider provider = mProviders.mProviders.get(component);
3756            return provider != null
3757                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3758                    : false;
3759        } else if (type == TYPE_UNKNOWN) {
3760            return isComponentVisibleToInstantApp(component);
3761        }
3762        return false;
3763    }
3764
3765    /**
3766     * Returns whether or not access to the application should be filtered.
3767     * <p>
3768     * Access may be limited based upon whether the calling or target applications
3769     * are instant applications.
3770     *
3771     * @see #canAccessInstantApps(int)
3772     */
3773    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
3774            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
3775        // if we're in an isolated process, get the real calling UID
3776        if (Process.isIsolated(callingUid)) {
3777            callingUid = mIsolatedOwners.get(callingUid);
3778        }
3779        final String instantAppPkgName = getInstantAppPackageName(callingUid);
3780        final boolean callerIsInstantApp = instantAppPkgName != null;
3781        if (ps == null) {
3782            if (callerIsInstantApp) {
3783                // pretend the application exists, but, needs to be filtered
3784                return true;
3785            }
3786            return false;
3787        }
3788        // if the target and caller are the same application, don't filter
3789        if (isCallerSameApp(ps.name, callingUid)) {
3790            return false;
3791        }
3792        if (callerIsInstantApp) {
3793            // request for a specific component; if it hasn't been explicitly exposed, filter
3794            if (component != null) {
3795                return !isComponentVisibleToInstantApp(component, componentType);
3796            }
3797            // request for application; if no components have been explicitly exposed, filter
3798            return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps;
3799        }
3800        if (ps.getInstantApp(userId)) {
3801            // caller can see all components of all instant applications, don't filter
3802            if (canViewInstantApps(callingUid, userId)) {
3803                return false;
3804            }
3805            // request for a specific instant application component, filter
3806            if (component != null) {
3807                return true;
3808            }
3809            // request for an instant application; if the caller hasn't been granted access, filter
3810            return !mInstantAppRegistry.isInstantAccessGranted(
3811                    userId, UserHandle.getAppId(callingUid), ps.appId);
3812        }
3813        return false;
3814    }
3815
3816    /**
3817     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
3818     */
3819    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
3820        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
3821    }
3822
3823    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
3824            int flags) {
3825        // Callers can access only the libs they depend on, otherwise they need to explicitly
3826        // ask for the shared libraries given the caller is allowed to access all static libs.
3827        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
3828            // System/shell/root get to see all static libs
3829            final int appId = UserHandle.getAppId(uid);
3830            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
3831                    || appId == Process.ROOT_UID) {
3832                return false;
3833            }
3834        }
3835
3836        // No package means no static lib as it is always on internal storage
3837        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
3838            return false;
3839        }
3840
3841        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
3842                ps.pkg.staticSharedLibVersion);
3843        if (libEntry == null) {
3844            return false;
3845        }
3846
3847        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
3848        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
3849        if (uidPackageNames == null) {
3850            return true;
3851        }
3852
3853        for (String uidPackageName : uidPackageNames) {
3854            if (ps.name.equals(uidPackageName)) {
3855                return false;
3856            }
3857            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
3858            if (uidPs != null) {
3859                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
3860                        libEntry.info.getName());
3861                if (index < 0) {
3862                    continue;
3863                }
3864                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
3865                    return false;
3866                }
3867            }
3868        }
3869        return true;
3870    }
3871
3872    @Override
3873    public String[] currentToCanonicalPackageNames(String[] names) {
3874        final int callingUid = Binder.getCallingUid();
3875        if (getInstantAppPackageName(callingUid) != null) {
3876            return names;
3877        }
3878        final String[] out = new String[names.length];
3879        // reader
3880        synchronized (mPackages) {
3881            final int callingUserId = UserHandle.getUserId(callingUid);
3882            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
3883            for (int i=names.length-1; i>=0; i--) {
3884                final PackageSetting ps = mSettings.mPackages.get(names[i]);
3885                boolean translateName = false;
3886                if (ps != null && ps.realName != null) {
3887                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
3888                    translateName = !targetIsInstantApp
3889                            || canViewInstantApps
3890                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
3891                                    UserHandle.getAppId(callingUid), ps.appId);
3892                }
3893                out[i] = translateName ? ps.realName : names[i];
3894            }
3895        }
3896        return out;
3897    }
3898
3899    @Override
3900    public String[] canonicalToCurrentPackageNames(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 String cur = mSettings.getRenamedPackageLPr(names[i]);
3912                boolean translateName = false;
3913                if (cur != null) {
3914                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
3915                    final boolean targetIsInstantApp =
3916                            ps != null && ps.getInstantApp(callingUserId);
3917                    translateName = !targetIsInstantApp
3918                            || canViewInstantApps
3919                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
3920                                    UserHandle.getAppId(callingUid), ps.appId);
3921                }
3922                out[i] = translateName ? cur : names[i];
3923            }
3924        }
3925        return out;
3926    }
3927
3928    @Override
3929    public int getPackageUid(String packageName, int flags, int userId) {
3930        if (!sUserManager.exists(userId)) return -1;
3931        final int callingUid = Binder.getCallingUid();
3932        flags = updateFlagsForPackage(flags, userId, packageName);
3933        enforceCrossUserPermission(callingUid, userId,
3934                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
3935
3936        // reader
3937        synchronized (mPackages) {
3938            final PackageParser.Package p = mPackages.get(packageName);
3939            if (p != null && p.isMatch(flags)) {
3940                PackageSetting ps = (PackageSetting) p.mExtras;
3941                if (filterAppAccessLPr(ps, callingUid, userId)) {
3942                    return -1;
3943                }
3944                return UserHandle.getUid(userId, p.applicationInfo.uid);
3945            }
3946            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3947                final PackageSetting ps = mSettings.mPackages.get(packageName);
3948                if (ps != null && ps.isMatch(flags)
3949                        && !filterAppAccessLPr(ps, callingUid, userId)) {
3950                    return UserHandle.getUid(userId, ps.appId);
3951                }
3952            }
3953        }
3954
3955        return -1;
3956    }
3957
3958    @Override
3959    public int[] getPackageGids(String packageName, int flags, int userId) {
3960        if (!sUserManager.exists(userId)) return null;
3961        final int callingUid = Binder.getCallingUid();
3962        flags = updateFlagsForPackage(flags, userId, packageName);
3963        enforceCrossUserPermission(callingUid, userId,
3964                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
3965
3966        // reader
3967        synchronized (mPackages) {
3968            final PackageParser.Package p = mPackages.get(packageName);
3969            if (p != null && p.isMatch(flags)) {
3970                PackageSetting ps = (PackageSetting) p.mExtras;
3971                if (filterAppAccessLPr(ps, callingUid, userId)) {
3972                    return null;
3973                }
3974                // TODO: Shouldn't this be checking for package installed state for userId and
3975                // return null?
3976                return ps.getPermissionsState().computeGids(userId);
3977            }
3978            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3979                final PackageSetting ps = mSettings.mPackages.get(packageName);
3980                if (ps != null && ps.isMatch(flags)
3981                        && !filterAppAccessLPr(ps, callingUid, userId)) {
3982                    return ps.getPermissionsState().computeGids(userId);
3983                }
3984            }
3985        }
3986
3987        return null;
3988    }
3989
3990    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3991        if (bp.perm != null) {
3992            return PackageParser.generatePermissionInfo(bp.perm, flags);
3993        }
3994        PermissionInfo pi = new PermissionInfo();
3995        pi.name = bp.name;
3996        pi.packageName = bp.sourcePackage;
3997        pi.nonLocalizedLabel = bp.name;
3998        pi.protectionLevel = bp.protectionLevel;
3999        return pi;
4000    }
4001
4002    @Override
4003    public PermissionInfo getPermissionInfo(String name, String packageName, int flags) {
4004        final int callingUid = Binder.getCallingUid();
4005        if (getInstantAppPackageName(callingUid) != null) {
4006            return null;
4007        }
4008        // reader
4009        synchronized (mPackages) {
4010            final BasePermission p = mSettings.mPermissions.get(name);
4011            if (p == null) {
4012                return null;
4013            }
4014            // If the caller is an app that targets pre 26 SDK drop protection flags.
4015            final PermissionInfo permissionInfo = generatePermissionInfo(p, flags);
4016            if (permissionInfo != null) {
4017                permissionInfo.protectionLevel = adjustPermissionProtectionFlagsLPr(
4018                        permissionInfo.protectionLevel, packageName, callingUid);
4019            }
4020            return permissionInfo;
4021        }
4022    }
4023
4024    private int adjustPermissionProtectionFlagsLPr(int protectionLevel,
4025            String packageName, int uid) {
4026        // Signature permission flags area always reported
4027        final int protectionLevelMasked = protectionLevel
4028                & (PermissionInfo.PROTECTION_NORMAL
4029                | PermissionInfo.PROTECTION_DANGEROUS
4030                | PermissionInfo.PROTECTION_SIGNATURE);
4031        if (protectionLevelMasked == PermissionInfo.PROTECTION_SIGNATURE) {
4032            return protectionLevel;
4033        }
4034
4035        // System sees all flags.
4036        final int appId = UserHandle.getAppId(uid);
4037        if (appId == Process.SYSTEM_UID || appId == Process.ROOT_UID
4038                || appId == Process.SHELL_UID) {
4039            return protectionLevel;
4040        }
4041
4042        // Normalize package name to handle renamed packages and static libs
4043        packageName = resolveInternalPackageNameLPr(packageName,
4044                PackageManager.VERSION_CODE_HIGHEST);
4045
4046        // Apps that target O see flags for all protection levels.
4047        final PackageSetting ps = mSettings.mPackages.get(packageName);
4048        if (ps == null) {
4049            return protectionLevel;
4050        }
4051        if (ps.appId != appId) {
4052            return protectionLevel;
4053        }
4054
4055        final PackageParser.Package pkg = mPackages.get(packageName);
4056        if (pkg == null) {
4057            return protectionLevel;
4058        }
4059        if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
4060            return protectionLevelMasked;
4061        }
4062
4063        return protectionLevel;
4064    }
4065
4066    @Override
4067    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
4068            int flags) {
4069        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4070            return null;
4071        }
4072        // reader
4073        synchronized (mPackages) {
4074            if (group != null && !mPermissionGroups.containsKey(group)) {
4075                // This is thrown as NameNotFoundException
4076                return null;
4077            }
4078
4079            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
4080            for (BasePermission p : mSettings.mPermissions.values()) {
4081                if (group == null) {
4082                    if (p.perm == null || p.perm.info.group == null) {
4083                        out.add(generatePermissionInfo(p, flags));
4084                    }
4085                } else {
4086                    if (p.perm != null && group.equals(p.perm.info.group)) {
4087                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
4088                    }
4089                }
4090            }
4091            return new ParceledListSlice<>(out);
4092        }
4093    }
4094
4095    @Override
4096    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
4097        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4098            return null;
4099        }
4100        // reader
4101        synchronized (mPackages) {
4102            return PackageParser.generatePermissionGroupInfo(
4103                    mPermissionGroups.get(name), flags);
4104        }
4105    }
4106
4107    @Override
4108    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4109        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4110            return ParceledListSlice.emptyList();
4111        }
4112        // reader
4113        synchronized (mPackages) {
4114            final int N = mPermissionGroups.size();
4115            ArrayList<PermissionGroupInfo> out
4116                    = new ArrayList<PermissionGroupInfo>(N);
4117            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
4118                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
4119            }
4120            return new ParceledListSlice<>(out);
4121        }
4122    }
4123
4124    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4125            int filterCallingUid, int userId) {
4126        if (!sUserManager.exists(userId)) return null;
4127        PackageSetting ps = mSettings.mPackages.get(packageName);
4128        if (ps != null) {
4129            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4130                return null;
4131            }
4132            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4133                return null;
4134            }
4135            if (ps.pkg == null) {
4136                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4137                if (pInfo != null) {
4138                    return pInfo.applicationInfo;
4139                }
4140                return null;
4141            }
4142            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4143                    ps.readUserState(userId), userId);
4144            if (ai != null) {
4145                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4146            }
4147            return ai;
4148        }
4149        return null;
4150    }
4151
4152    @Override
4153    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4154        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4155    }
4156
4157    /**
4158     * Important: The provided filterCallingUid is used exclusively to filter out applications
4159     * that can be seen based on user state. It's typically the original caller uid prior
4160     * to clearing. Because it can only be provided by trusted code, it's value can be
4161     * trusted and will be used as-is; unlike userId which will be validated by this method.
4162     */
4163    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4164            int filterCallingUid, int userId) {
4165        if (!sUserManager.exists(userId)) return null;
4166        flags = updateFlagsForApplication(flags, userId, packageName);
4167        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4168                false /* requireFullPermission */, false /* checkShell */, "get application info");
4169
4170        // writer
4171        synchronized (mPackages) {
4172            // Normalize package name to handle renamed packages and static libs
4173            packageName = resolveInternalPackageNameLPr(packageName,
4174                    PackageManager.VERSION_CODE_HIGHEST);
4175
4176            PackageParser.Package p = mPackages.get(packageName);
4177            if (DEBUG_PACKAGE_INFO) Log.v(
4178                    TAG, "getApplicationInfo " + packageName
4179                    + ": " + p);
4180            if (p != null) {
4181                PackageSetting ps = mSettings.mPackages.get(packageName);
4182                if (ps == null) return null;
4183                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4184                    return null;
4185                }
4186                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4187                    return null;
4188                }
4189                // Note: isEnabledLP() does not apply here - always return info
4190                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4191                        p, flags, ps.readUserState(userId), userId);
4192                if (ai != null) {
4193                    ai.packageName = resolveExternalPackageNameLPr(p);
4194                }
4195                return ai;
4196            }
4197            if ("android".equals(packageName)||"system".equals(packageName)) {
4198                return mAndroidApplication;
4199            }
4200            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4201                // Already generates the external package name
4202                return generateApplicationInfoFromSettingsLPw(packageName,
4203                        flags, filterCallingUid, userId);
4204            }
4205        }
4206        return null;
4207    }
4208
4209    private String normalizePackageNameLPr(String packageName) {
4210        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4211        return normalizedPackageName != null ? normalizedPackageName : packageName;
4212    }
4213
4214    @Override
4215    public void deletePreloadsFileCache() {
4216        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4217            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4218        }
4219        File dir = Environment.getDataPreloadsFileCacheDirectory();
4220        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4221        FileUtils.deleteContents(dir);
4222    }
4223
4224    @Override
4225    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4226            final int storageFlags, final IPackageDataObserver observer) {
4227        mContext.enforceCallingOrSelfPermission(
4228                android.Manifest.permission.CLEAR_APP_CACHE, null);
4229        mHandler.post(() -> {
4230            boolean success = false;
4231            try {
4232                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4233                success = true;
4234            } catch (IOException e) {
4235                Slog.w(TAG, e);
4236            }
4237            if (observer != null) {
4238                try {
4239                    observer.onRemoveCompleted(null, success);
4240                } catch (RemoteException e) {
4241                    Slog.w(TAG, e);
4242                }
4243            }
4244        });
4245    }
4246
4247    @Override
4248    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4249            final int storageFlags, final IntentSender pi) {
4250        mContext.enforceCallingOrSelfPermission(
4251                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4252        mHandler.post(() -> {
4253            boolean success = false;
4254            try {
4255                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4256                success = true;
4257            } catch (IOException e) {
4258                Slog.w(TAG, e);
4259            }
4260            if (pi != null) {
4261                try {
4262                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4263                } catch (SendIntentException e) {
4264                    Slog.w(TAG, e);
4265                }
4266            }
4267        });
4268    }
4269
4270    /**
4271     * Blocking call to clear various types of cached data across the system
4272     * until the requested bytes are available.
4273     */
4274    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4275        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4276        final File file = storage.findPathForUuid(volumeUuid);
4277        if (file.getUsableSpace() >= bytes) return;
4278
4279        if (ENABLE_FREE_CACHE_V2) {
4280            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4281                    volumeUuid);
4282            final boolean aggressive = (storageFlags
4283                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4284            final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags);
4285
4286            // 1. Pre-flight to determine if we have any chance to succeed
4287            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4288            if (internalVolume && (aggressive || SystemProperties
4289                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4290                deletePreloadsFileCache();
4291                if (file.getUsableSpace() >= bytes) return;
4292            }
4293
4294            // 3. Consider parsed APK data (aggressive only)
4295            if (internalVolume && aggressive) {
4296                FileUtils.deleteContents(mCacheDir);
4297                if (file.getUsableSpace() >= bytes) return;
4298            }
4299
4300            // 4. Consider cached app data (above quotas)
4301            try {
4302                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4303                        Installer.FLAG_FREE_CACHE_V2);
4304            } catch (InstallerException ignored) {
4305            }
4306            if (file.getUsableSpace() >= bytes) return;
4307
4308            // 5. Consider shared libraries with refcount=0 and age>min cache period
4309            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4310                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4311                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4312                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4313                return;
4314            }
4315
4316            // 6. Consider dexopt output (aggressive only)
4317            // TODO: Implement
4318
4319            // 7. Consider installed instant apps unused longer than min cache period
4320            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4321                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4322                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4323                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4324                return;
4325            }
4326
4327            // 8. Consider cached app data (below quotas)
4328            try {
4329                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4330                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4331            } catch (InstallerException ignored) {
4332            }
4333            if (file.getUsableSpace() >= bytes) return;
4334
4335            // 9. Consider DropBox entries
4336            // TODO: Implement
4337
4338            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4339            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4340                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4341                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4342                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4343                return;
4344            }
4345        } else {
4346            try {
4347                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4348            } catch (InstallerException ignored) {
4349            }
4350            if (file.getUsableSpace() >= bytes) return;
4351        }
4352
4353        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4354    }
4355
4356    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4357            throws IOException {
4358        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4359        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4360
4361        List<VersionedPackage> packagesToDelete = null;
4362        final long now = System.currentTimeMillis();
4363
4364        synchronized (mPackages) {
4365            final int[] allUsers = sUserManager.getUserIds();
4366            final int libCount = mSharedLibraries.size();
4367            for (int i = 0; i < libCount; i++) {
4368                final SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4369                if (versionedLib == null) {
4370                    continue;
4371                }
4372                final int versionCount = versionedLib.size();
4373                for (int j = 0; j < versionCount; j++) {
4374                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4375                    // Skip packages that are not static shared libs.
4376                    if (!libInfo.isStatic()) {
4377                        break;
4378                    }
4379                    // Important: We skip static shared libs used for some user since
4380                    // in such a case we need to keep the APK on the device. The check for
4381                    // a lib being used for any user is performed by the uninstall call.
4382                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4383                    // Resolve the package name - we use synthetic package names internally
4384                    final String internalPackageName = resolveInternalPackageNameLPr(
4385                            declaringPackage.getPackageName(), declaringPackage.getVersionCode());
4386                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4387                    // Skip unused static shared libs cached less than the min period
4388                    // to prevent pruning a lib needed by a subsequently installed package.
4389                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4390                        continue;
4391                    }
4392                    if (packagesToDelete == null) {
4393                        packagesToDelete = new ArrayList<>();
4394                    }
4395                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4396                            declaringPackage.getVersionCode()));
4397                }
4398            }
4399        }
4400
4401        if (packagesToDelete != null) {
4402            final int packageCount = packagesToDelete.size();
4403            for (int i = 0; i < packageCount; i++) {
4404                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4405                // Delete the package synchronously (will fail of the lib used for any user).
4406                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getVersionCode(),
4407                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4408                                == PackageManager.DELETE_SUCCEEDED) {
4409                    if (volume.getUsableSpace() >= neededSpace) {
4410                        return true;
4411                    }
4412                }
4413            }
4414        }
4415
4416        return false;
4417    }
4418
4419    /**
4420     * Update given flags based on encryption status of current user.
4421     */
4422    private int updateFlags(int flags, int userId) {
4423        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4424                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4425            // Caller expressed an explicit opinion about what encryption
4426            // aware/unaware components they want to see, so fall through and
4427            // give them what they want
4428        } else {
4429            // Caller expressed no opinion, so match based on user state
4430            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4431                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4432            } else {
4433                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4434            }
4435        }
4436        return flags;
4437    }
4438
4439    private UserManagerInternal getUserManagerInternal() {
4440        if (mUserManagerInternal == null) {
4441            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4442        }
4443        return mUserManagerInternal;
4444    }
4445
4446    private DeviceIdleController.LocalService getDeviceIdleController() {
4447        if (mDeviceIdleController == null) {
4448            mDeviceIdleController =
4449                    LocalServices.getService(DeviceIdleController.LocalService.class);
4450        }
4451        return mDeviceIdleController;
4452    }
4453
4454    /**
4455     * Update given flags when being used to request {@link PackageInfo}.
4456     */
4457    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4458        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4459        boolean triaged = true;
4460        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4461                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4462            // Caller is asking for component details, so they'd better be
4463            // asking for specific encryption matching behavior, or be triaged
4464            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4465                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4466                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4467                triaged = false;
4468            }
4469        }
4470        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4471                | PackageManager.MATCH_SYSTEM_ONLY
4472                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4473            triaged = false;
4474        }
4475        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4476            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
4477                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4478                    + Debug.getCallers(5));
4479        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4480                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4481            // If the caller wants all packages and has a restricted profile associated with it,
4482            // then match all users. This is to make sure that launchers that need to access work
4483            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4484            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4485            flags |= PackageManager.MATCH_ANY_USER;
4486        }
4487        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4488            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4489                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4490        }
4491        return updateFlags(flags, userId);
4492    }
4493
4494    /**
4495     * Update given flags when being used to request {@link ApplicationInfo}.
4496     */
4497    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4498        return updateFlagsForPackage(flags, userId, cookie);
4499    }
4500
4501    /**
4502     * Update given flags when being used to request {@link ComponentInfo}.
4503     */
4504    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4505        if (cookie instanceof Intent) {
4506            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4507                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4508            }
4509        }
4510
4511        boolean triaged = true;
4512        // Caller is asking for component details, so they'd better be
4513        // asking for specific encryption matching behavior, or be triaged
4514        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4515                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4516                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4517            triaged = false;
4518        }
4519        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4520            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4521                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4522        }
4523
4524        return updateFlags(flags, userId);
4525    }
4526
4527    /**
4528     * Update given intent when being used to request {@link ResolveInfo}.
4529     */
4530    private Intent updateIntentForResolve(Intent intent) {
4531        if (intent.getSelector() != null) {
4532            intent = intent.getSelector();
4533        }
4534        if (DEBUG_PREFERRED) {
4535            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4536        }
4537        return intent;
4538    }
4539
4540    /**
4541     * Update given flags when being used to request {@link ResolveInfo}.
4542     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4543     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4544     * flag set. However, this flag is only honoured in three circumstances:
4545     * <ul>
4546     * <li>when called from a system process</li>
4547     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4548     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4549     * action and a {@code android.intent.category.BROWSABLE} category</li>
4550     * </ul>
4551     */
4552    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4553        return updateFlagsForResolve(flags, userId, intent, callingUid,
4554                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4555    }
4556    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4557            boolean wantInstantApps) {
4558        return updateFlagsForResolve(flags, userId, intent, callingUid,
4559                wantInstantApps, false /*onlyExposedExplicitly*/);
4560    }
4561    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4562            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4563        // Safe mode means we shouldn't match any third-party components
4564        if (mSafeMode) {
4565            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4566        }
4567        if (getInstantAppPackageName(callingUid) != null) {
4568            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4569            if (onlyExposedExplicitly) {
4570                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4571            }
4572            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4573            flags |= PackageManager.MATCH_INSTANT;
4574        } else {
4575            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4576            final boolean allowMatchInstant =
4577                    (wantInstantApps
4578                            && Intent.ACTION_VIEW.equals(intent.getAction())
4579                            && hasWebURI(intent))
4580                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4581            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4582                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4583            if (!allowMatchInstant) {
4584                flags &= ~PackageManager.MATCH_INSTANT;
4585            }
4586        }
4587        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4588    }
4589
4590    @Override
4591    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4592        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4593    }
4594
4595    /**
4596     * Important: The provided filterCallingUid is used exclusively to filter out activities
4597     * that can be seen based on user state. It's typically the original caller uid prior
4598     * to clearing. Because it can only be provided by trusted code, it's value can be
4599     * trusted and will be used as-is; unlike userId which will be validated by this method.
4600     */
4601    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4602            int filterCallingUid, int userId) {
4603        if (!sUserManager.exists(userId)) return null;
4604        flags = updateFlagsForComponent(flags, userId, component);
4605        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4606                false /* requireFullPermission */, false /* checkShell */, "get activity info");
4607        synchronized (mPackages) {
4608            PackageParser.Activity a = mActivities.mActivities.get(component);
4609
4610            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4611            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4612                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4613                if (ps == null) return null;
4614                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4615                    return null;
4616                }
4617                return PackageParser.generateActivityInfo(
4618                        a, flags, ps.readUserState(userId), userId);
4619            }
4620            if (mResolveComponentName.equals(component)) {
4621                return PackageParser.generateActivityInfo(
4622                        mResolveActivity, flags, new PackageUserState(), userId);
4623            }
4624        }
4625        return null;
4626    }
4627
4628    @Override
4629    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4630            String resolvedType) {
4631        synchronized (mPackages) {
4632            if (component.equals(mResolveComponentName)) {
4633                // The resolver supports EVERYTHING!
4634                return true;
4635            }
4636            final int callingUid = Binder.getCallingUid();
4637            final int callingUserId = UserHandle.getUserId(callingUid);
4638            PackageParser.Activity a = mActivities.mActivities.get(component);
4639            if (a == null) {
4640                return false;
4641            }
4642            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4643            if (ps == null) {
4644                return false;
4645            }
4646            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4647                return false;
4648            }
4649            for (int i=0; i<a.intents.size(); i++) {
4650                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4651                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4652                    return true;
4653                }
4654            }
4655            return false;
4656        }
4657    }
4658
4659    @Override
4660    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4661        if (!sUserManager.exists(userId)) return null;
4662        final int callingUid = Binder.getCallingUid();
4663        flags = updateFlagsForComponent(flags, userId, component);
4664        enforceCrossUserPermission(callingUid, userId,
4665                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4666        synchronized (mPackages) {
4667            PackageParser.Activity a = mReceivers.mActivities.get(component);
4668            if (DEBUG_PACKAGE_INFO) Log.v(
4669                TAG, "getReceiverInfo " + component + ": " + a);
4670            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4671                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4672                if (ps == null) return null;
4673                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4674                    return null;
4675                }
4676                return PackageParser.generateActivityInfo(
4677                        a, flags, ps.readUserState(userId), userId);
4678            }
4679        }
4680        return null;
4681    }
4682
4683    @Override
4684    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4685            int flags, int userId) {
4686        if (!sUserManager.exists(userId)) return null;
4687        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4688        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4689            return null;
4690        }
4691
4692        flags = updateFlagsForPackage(flags, userId, null);
4693
4694        final boolean canSeeStaticLibraries =
4695                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4696                        == PERMISSION_GRANTED
4697                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4698                        == PERMISSION_GRANTED
4699                || canRequestPackageInstallsInternal(packageName,
4700                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
4701                        false  /* throwIfPermNotDeclared*/)
4702                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4703                        == PERMISSION_GRANTED;
4704
4705        synchronized (mPackages) {
4706            List<SharedLibraryInfo> result = null;
4707
4708            final int libCount = mSharedLibraries.size();
4709            for (int i = 0; i < libCount; i++) {
4710                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4711                if (versionedLib == null) {
4712                    continue;
4713                }
4714
4715                final int versionCount = versionedLib.size();
4716                for (int j = 0; j < versionCount; j++) {
4717                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4718                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4719                        break;
4720                    }
4721                    final long identity = Binder.clearCallingIdentity();
4722                    try {
4723                        PackageInfo packageInfo = getPackageInfoVersioned(
4724                                libInfo.getDeclaringPackage(), flags
4725                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
4726                        if (packageInfo == null) {
4727                            continue;
4728                        }
4729                    } finally {
4730                        Binder.restoreCallingIdentity(identity);
4731                    }
4732
4733                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4734                            libInfo.getVersion(), libInfo.getType(),
4735                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
4736                            flags, userId));
4737
4738                    if (result == null) {
4739                        result = new ArrayList<>();
4740                    }
4741                    result.add(resLibInfo);
4742                }
4743            }
4744
4745            return result != null ? new ParceledListSlice<>(result) : null;
4746        }
4747    }
4748
4749    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4750            SharedLibraryInfo libInfo, int flags, int userId) {
4751        List<VersionedPackage> versionedPackages = null;
4752        final int packageCount = mSettings.mPackages.size();
4753        for (int i = 0; i < packageCount; i++) {
4754            PackageSetting ps = mSettings.mPackages.valueAt(i);
4755
4756            if (ps == null) {
4757                continue;
4758            }
4759
4760            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4761                continue;
4762            }
4763
4764            final String libName = libInfo.getName();
4765            if (libInfo.isStatic()) {
4766                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4767                if (libIdx < 0) {
4768                    continue;
4769                }
4770                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
4771                    continue;
4772                }
4773                if (versionedPackages == null) {
4774                    versionedPackages = new ArrayList<>();
4775                }
4776                // If the dependent is a static shared lib, use the public package name
4777                String dependentPackageName = ps.name;
4778                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4779                    dependentPackageName = ps.pkg.manifestPackageName;
4780                }
4781                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
4782            } else if (ps.pkg != null) {
4783                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
4784                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
4785                    if (versionedPackages == null) {
4786                        versionedPackages = new ArrayList<>();
4787                    }
4788                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
4789                }
4790            }
4791        }
4792
4793        return versionedPackages;
4794    }
4795
4796    @Override
4797    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
4798        if (!sUserManager.exists(userId)) return null;
4799        final int callingUid = Binder.getCallingUid();
4800        flags = updateFlagsForComponent(flags, userId, component);
4801        enforceCrossUserPermission(callingUid, userId,
4802                false /* requireFullPermission */, false /* checkShell */, "get service info");
4803        synchronized (mPackages) {
4804            PackageParser.Service s = mServices.mServices.get(component);
4805            if (DEBUG_PACKAGE_INFO) Log.v(
4806                TAG, "getServiceInfo " + component + ": " + s);
4807            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
4808                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4809                if (ps == null) return null;
4810                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
4811                    return null;
4812                }
4813                return PackageParser.generateServiceInfo(
4814                        s, flags, ps.readUserState(userId), userId);
4815            }
4816        }
4817        return null;
4818    }
4819
4820    @Override
4821    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
4822        if (!sUserManager.exists(userId)) return null;
4823        final int callingUid = Binder.getCallingUid();
4824        flags = updateFlagsForComponent(flags, userId, component);
4825        enforceCrossUserPermission(callingUid, userId,
4826                false /* requireFullPermission */, false /* checkShell */, "get provider info");
4827        synchronized (mPackages) {
4828            PackageParser.Provider p = mProviders.mProviders.get(component);
4829            if (DEBUG_PACKAGE_INFO) Log.v(
4830                TAG, "getProviderInfo " + component + ": " + p);
4831            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
4832                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4833                if (ps == null) return null;
4834                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
4835                    return null;
4836                }
4837                return PackageParser.generateProviderInfo(
4838                        p, flags, ps.readUserState(userId), userId);
4839            }
4840        }
4841        return null;
4842    }
4843
4844    @Override
4845    public String[] getSystemSharedLibraryNames() {
4846        // allow instant applications
4847        synchronized (mPackages) {
4848            Set<String> libs = null;
4849            final int libCount = mSharedLibraries.size();
4850            for (int i = 0; i < libCount; i++) {
4851                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4852                if (versionedLib == null) {
4853                    continue;
4854                }
4855                final int versionCount = versionedLib.size();
4856                for (int j = 0; j < versionCount; j++) {
4857                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
4858                    if (!libEntry.info.isStatic()) {
4859                        if (libs == null) {
4860                            libs = new ArraySet<>();
4861                        }
4862                        libs.add(libEntry.info.getName());
4863                        break;
4864                    }
4865                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
4866                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
4867                            UserHandle.getUserId(Binder.getCallingUid()),
4868                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
4869                        if (libs == null) {
4870                            libs = new ArraySet<>();
4871                        }
4872                        libs.add(libEntry.info.getName());
4873                        break;
4874                    }
4875                }
4876            }
4877
4878            if (libs != null) {
4879                String[] libsArray = new String[libs.size()];
4880                libs.toArray(libsArray);
4881                return libsArray;
4882            }
4883
4884            return null;
4885        }
4886    }
4887
4888    @Override
4889    public @NonNull String getServicesSystemSharedLibraryPackageName() {
4890        // allow instant applications
4891        synchronized (mPackages) {
4892            return mServicesSystemSharedLibraryPackageName;
4893        }
4894    }
4895
4896    @Override
4897    public @NonNull String getSharedSystemSharedLibraryPackageName() {
4898        // allow instant applications
4899        synchronized (mPackages) {
4900            return mSharedSystemSharedLibraryPackageName;
4901        }
4902    }
4903
4904    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
4905        for (int i = userList.length - 1; i >= 0; --i) {
4906            final int userId = userList[i];
4907            // don't add instant app to the list of updates
4908            if (pkgSetting.getInstantApp(userId)) {
4909                continue;
4910            }
4911            SparseArray<String> changedPackages = mChangedPackages.get(userId);
4912            if (changedPackages == null) {
4913                changedPackages = new SparseArray<>();
4914                mChangedPackages.put(userId, changedPackages);
4915            }
4916            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
4917            if (sequenceNumbers == null) {
4918                sequenceNumbers = new HashMap<>();
4919                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
4920            }
4921            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
4922            if (sequenceNumber != null) {
4923                changedPackages.remove(sequenceNumber);
4924            }
4925            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
4926            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
4927        }
4928        mChangedPackagesSequenceNumber++;
4929    }
4930
4931    @Override
4932    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
4933        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4934            return null;
4935        }
4936        synchronized (mPackages) {
4937            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
4938                return null;
4939            }
4940            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
4941            if (changedPackages == null) {
4942                return null;
4943            }
4944            final List<String> packageNames =
4945                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
4946            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
4947                final String packageName = changedPackages.get(i);
4948                if (packageName != null) {
4949                    packageNames.add(packageName);
4950                }
4951            }
4952            return packageNames.isEmpty()
4953                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
4954        }
4955    }
4956
4957    @Override
4958    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
4959        // allow instant applications
4960        ArrayList<FeatureInfo> res;
4961        synchronized (mAvailableFeatures) {
4962            res = new ArrayList<>(mAvailableFeatures.size() + 1);
4963            res.addAll(mAvailableFeatures.values());
4964        }
4965        final FeatureInfo fi = new FeatureInfo();
4966        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
4967                FeatureInfo.GL_ES_VERSION_UNDEFINED);
4968        res.add(fi);
4969
4970        return new ParceledListSlice<>(res);
4971    }
4972
4973    @Override
4974    public boolean hasSystemFeature(String name, int version) {
4975        // allow instant applications
4976        synchronized (mAvailableFeatures) {
4977            final FeatureInfo feat = mAvailableFeatures.get(name);
4978            if (feat == null) {
4979                return false;
4980            } else {
4981                return feat.version >= version;
4982            }
4983        }
4984    }
4985
4986    @Override
4987    public int checkPermission(String permName, String pkgName, int userId) {
4988        if (!sUserManager.exists(userId)) {
4989            return PackageManager.PERMISSION_DENIED;
4990        }
4991        final int callingUid = Binder.getCallingUid();
4992
4993        synchronized (mPackages) {
4994            final PackageParser.Package p = mPackages.get(pkgName);
4995            if (p != null && p.mExtras != null) {
4996                final PackageSetting ps = (PackageSetting) p.mExtras;
4997                if (filterAppAccessLPr(ps, callingUid, userId)) {
4998                    return PackageManager.PERMISSION_DENIED;
4999                }
5000                final boolean instantApp = ps.getInstantApp(userId);
5001                final PermissionsState permissionsState = ps.getPermissionsState();
5002                if (permissionsState.hasPermission(permName, userId)) {
5003                    if (instantApp) {
5004                        BasePermission bp = mSettings.mPermissions.get(permName);
5005                        if (bp != null && bp.isInstant()) {
5006                            return PackageManager.PERMISSION_GRANTED;
5007                        }
5008                    } else {
5009                        return PackageManager.PERMISSION_GRANTED;
5010                    }
5011                }
5012                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5013                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5014                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5015                    return PackageManager.PERMISSION_GRANTED;
5016                }
5017            }
5018        }
5019
5020        return PackageManager.PERMISSION_DENIED;
5021    }
5022
5023    @Override
5024    public int checkUidPermission(String permName, int uid) {
5025        final int callingUid = Binder.getCallingUid();
5026        final int callingUserId = UserHandle.getUserId(callingUid);
5027        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5028        final boolean isUidInstantApp = getInstantAppPackageName(uid) != null;
5029        final int userId = UserHandle.getUserId(uid);
5030        if (!sUserManager.exists(userId)) {
5031            return PackageManager.PERMISSION_DENIED;
5032        }
5033
5034        synchronized (mPackages) {
5035            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5036            if (obj != null) {
5037                if (obj instanceof SharedUserSetting) {
5038                    if (isCallerInstantApp) {
5039                        return PackageManager.PERMISSION_DENIED;
5040                    }
5041                } else if (obj instanceof PackageSetting) {
5042                    final PackageSetting ps = (PackageSetting) obj;
5043                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5044                        return PackageManager.PERMISSION_DENIED;
5045                    }
5046                }
5047                final SettingBase settingBase = (SettingBase) obj;
5048                final PermissionsState permissionsState = settingBase.getPermissionsState();
5049                if (permissionsState.hasPermission(permName, userId)) {
5050                    if (isUidInstantApp) {
5051                        BasePermission bp = mSettings.mPermissions.get(permName);
5052                        if (bp != null && bp.isInstant()) {
5053                            return PackageManager.PERMISSION_GRANTED;
5054                        }
5055                    } else {
5056                        return PackageManager.PERMISSION_GRANTED;
5057                    }
5058                }
5059                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5060                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5061                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5062                    return PackageManager.PERMISSION_GRANTED;
5063                }
5064            } else {
5065                ArraySet<String> perms = mSystemPermissions.get(uid);
5066                if (perms != null) {
5067                    if (perms.contains(permName)) {
5068                        return PackageManager.PERMISSION_GRANTED;
5069                    }
5070                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
5071                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
5072                        return PackageManager.PERMISSION_GRANTED;
5073                    }
5074                }
5075            }
5076        }
5077
5078        return PackageManager.PERMISSION_DENIED;
5079    }
5080
5081    @Override
5082    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5083        if (UserHandle.getCallingUserId() != userId) {
5084            mContext.enforceCallingPermission(
5085                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5086                    "isPermissionRevokedByPolicy for user " + userId);
5087        }
5088
5089        if (checkPermission(permission, packageName, userId)
5090                == PackageManager.PERMISSION_GRANTED) {
5091            return false;
5092        }
5093
5094        final int callingUid = Binder.getCallingUid();
5095        if (getInstantAppPackageName(callingUid) != null) {
5096            if (!isCallerSameApp(packageName, callingUid)) {
5097                return false;
5098            }
5099        } else {
5100            if (isInstantApp(packageName, userId)) {
5101                return false;
5102            }
5103        }
5104
5105        final long identity = Binder.clearCallingIdentity();
5106        try {
5107            final int flags = getPermissionFlags(permission, packageName, userId);
5108            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5109        } finally {
5110            Binder.restoreCallingIdentity(identity);
5111        }
5112    }
5113
5114    @Override
5115    public String getPermissionControllerPackageName() {
5116        synchronized (mPackages) {
5117            return mRequiredInstallerPackage;
5118        }
5119    }
5120
5121    /**
5122     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
5123     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
5124     * @param checkShell whether to prevent shell from access if there's a debugging restriction
5125     * @param message the message to log on security exception
5126     */
5127    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
5128            boolean checkShell, String message) {
5129        if (userId < 0) {
5130            throw new IllegalArgumentException("Invalid userId " + userId);
5131        }
5132        if (checkShell) {
5133            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
5134        }
5135        if (userId == UserHandle.getUserId(callingUid)) return;
5136        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5137            if (requireFullPermission) {
5138                mContext.enforceCallingOrSelfPermission(
5139                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5140            } else {
5141                try {
5142                    mContext.enforceCallingOrSelfPermission(
5143                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5144                } catch (SecurityException se) {
5145                    mContext.enforceCallingOrSelfPermission(
5146                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
5147                }
5148            }
5149        }
5150    }
5151
5152    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
5153        if (callingUid == Process.SHELL_UID) {
5154            if (userHandle >= 0
5155                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
5156                throw new SecurityException("Shell does not have permission to access user "
5157                        + userHandle);
5158            } else if (userHandle < 0) {
5159                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
5160                        + Debug.getCallers(3));
5161            }
5162        }
5163    }
5164
5165    private BasePermission findPermissionTreeLP(String permName) {
5166        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
5167            if (permName.startsWith(bp.name) &&
5168                    permName.length() > bp.name.length() &&
5169                    permName.charAt(bp.name.length()) == '.') {
5170                return bp;
5171            }
5172        }
5173        return null;
5174    }
5175
5176    private BasePermission checkPermissionTreeLP(String permName) {
5177        if (permName != null) {
5178            BasePermission bp = findPermissionTreeLP(permName);
5179            if (bp != null) {
5180                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
5181                    return bp;
5182                }
5183                throw new SecurityException("Calling uid "
5184                        + Binder.getCallingUid()
5185                        + " is not allowed to add to permission tree "
5186                        + bp.name + " owned by uid " + bp.uid);
5187            }
5188        }
5189        throw new SecurityException("No permission tree found for " + permName);
5190    }
5191
5192    static boolean compareStrings(CharSequence s1, CharSequence s2) {
5193        if (s1 == null) {
5194            return s2 == null;
5195        }
5196        if (s2 == null) {
5197            return false;
5198        }
5199        if (s1.getClass() != s2.getClass()) {
5200            return false;
5201        }
5202        return s1.equals(s2);
5203    }
5204
5205    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
5206        if (pi1.icon != pi2.icon) return false;
5207        if (pi1.logo != pi2.logo) return false;
5208        if (pi1.protectionLevel != pi2.protectionLevel) return false;
5209        if (!compareStrings(pi1.name, pi2.name)) return false;
5210        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
5211        // We'll take care of setting this one.
5212        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
5213        // These are not currently stored in settings.
5214        //if (!compareStrings(pi1.group, pi2.group)) return false;
5215        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
5216        //if (pi1.labelRes != pi2.labelRes) return false;
5217        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
5218        return true;
5219    }
5220
5221    int permissionInfoFootprint(PermissionInfo info) {
5222        int size = info.name.length();
5223        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
5224        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
5225        return size;
5226    }
5227
5228    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
5229        int size = 0;
5230        for (BasePermission perm : mSettings.mPermissions.values()) {
5231            if (perm.uid == tree.uid) {
5232                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
5233            }
5234        }
5235        return size;
5236    }
5237
5238    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
5239        // We calculate the max size of permissions defined by this uid and throw
5240        // if that plus the size of 'info' would exceed our stated maximum.
5241        if (tree.uid != Process.SYSTEM_UID) {
5242            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
5243            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
5244                throw new SecurityException("Permission tree size cap exceeded");
5245            }
5246        }
5247    }
5248
5249    boolean addPermissionLocked(PermissionInfo info, boolean async) {
5250        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5251            throw new SecurityException("Instant apps can't add permissions");
5252        }
5253        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
5254            throw new SecurityException("Label must be specified in permission");
5255        }
5256        BasePermission tree = checkPermissionTreeLP(info.name);
5257        BasePermission bp = mSettings.mPermissions.get(info.name);
5258        boolean added = bp == null;
5259        boolean changed = true;
5260        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
5261        if (added) {
5262            enforcePermissionCapLocked(info, tree);
5263            bp = new BasePermission(info.name, tree.sourcePackage,
5264                    BasePermission.TYPE_DYNAMIC);
5265        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
5266            throw new SecurityException(
5267                    "Not allowed to modify non-dynamic permission "
5268                    + info.name);
5269        } else {
5270            if (bp.protectionLevel == fixedLevel
5271                    && bp.perm.owner.equals(tree.perm.owner)
5272                    && bp.uid == tree.uid
5273                    && comparePermissionInfos(bp.perm.info, info)) {
5274                changed = false;
5275            }
5276        }
5277        bp.protectionLevel = fixedLevel;
5278        info = new PermissionInfo(info);
5279        info.protectionLevel = fixedLevel;
5280        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
5281        bp.perm.info.packageName = tree.perm.info.packageName;
5282        bp.uid = tree.uid;
5283        if (added) {
5284            mSettings.mPermissions.put(info.name, bp);
5285        }
5286        if (changed) {
5287            if (!async) {
5288                mSettings.writeLPr();
5289            } else {
5290                scheduleWriteSettingsLocked();
5291            }
5292        }
5293        return added;
5294    }
5295
5296    @Override
5297    public boolean addPermission(PermissionInfo info) {
5298        synchronized (mPackages) {
5299            return addPermissionLocked(info, false);
5300        }
5301    }
5302
5303    @Override
5304    public boolean addPermissionAsync(PermissionInfo info) {
5305        synchronized (mPackages) {
5306            return addPermissionLocked(info, true);
5307        }
5308    }
5309
5310    @Override
5311    public void removePermission(String name) {
5312        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5313            throw new SecurityException("Instant applications don't have access to this method");
5314        }
5315        synchronized (mPackages) {
5316            checkPermissionTreeLP(name);
5317            BasePermission bp = mSettings.mPermissions.get(name);
5318            if (bp != null) {
5319                if (bp.type != BasePermission.TYPE_DYNAMIC) {
5320                    throw new SecurityException(
5321                            "Not allowed to modify non-dynamic permission "
5322                            + name);
5323                }
5324                mSettings.mPermissions.remove(name);
5325                mSettings.writeLPr();
5326            }
5327        }
5328    }
5329
5330    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(
5331            PackageParser.Package pkg, BasePermission bp) {
5332        int index = pkg.requestedPermissions.indexOf(bp.name);
5333        if (index == -1) {
5334            throw new SecurityException("Package " + pkg.packageName
5335                    + " has not requested permission " + bp.name);
5336        }
5337        if (!bp.isRuntime() && !bp.isDevelopment()) {
5338            throw new SecurityException("Permission " + bp.name
5339                    + " is not a changeable permission type");
5340        }
5341    }
5342
5343    @Override
5344    public void grantRuntimePermission(String packageName, String name, final int userId) {
5345        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5346    }
5347
5348    private void grantRuntimePermission(String packageName, String name, final int userId,
5349            boolean overridePolicy) {
5350        if (!sUserManager.exists(userId)) {
5351            Log.e(TAG, "No such user:" + userId);
5352            return;
5353        }
5354        final int callingUid = Binder.getCallingUid();
5355
5356        mContext.enforceCallingOrSelfPermission(
5357                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
5358                "grantRuntimePermission");
5359
5360        enforceCrossUserPermission(callingUid, userId,
5361                true /* requireFullPermission */, true /* checkShell */,
5362                "grantRuntimePermission");
5363
5364        final int uid;
5365        final PackageSetting ps;
5366
5367        synchronized (mPackages) {
5368            final PackageParser.Package pkg = mPackages.get(packageName);
5369            if (pkg == null) {
5370                throw new IllegalArgumentException("Unknown package: " + packageName);
5371            }
5372            final BasePermission bp = mSettings.mPermissions.get(name);
5373            if (bp == null) {
5374                throw new IllegalArgumentException("Unknown permission: " + name);
5375            }
5376            ps = (PackageSetting) pkg.mExtras;
5377            if (ps == null
5378                    || filterAppAccessLPr(ps, callingUid, userId)) {
5379                throw new IllegalArgumentException("Unknown package: " + packageName);
5380            }
5381
5382            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5383
5384            // If a permission review is required for legacy apps we represent
5385            // their permissions as always granted runtime ones since we need
5386            // to keep the review required permission flag per user while an
5387            // install permission's state is shared across all users.
5388            if (mPermissionReviewRequired
5389                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5390                    && bp.isRuntime()) {
5391                return;
5392            }
5393
5394            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
5395
5396            final PermissionsState permissionsState = ps.getPermissionsState();
5397
5398            final int flags = permissionsState.getPermissionFlags(name, userId);
5399            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5400                throw new SecurityException("Cannot grant system fixed permission "
5401                        + name + " for package " + packageName);
5402            }
5403            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5404                throw new SecurityException("Cannot grant policy fixed permission "
5405                        + name + " for package " + packageName);
5406            }
5407
5408            if (bp.isDevelopment()) {
5409                // Development permissions must be handled specially, since they are not
5410                // normal runtime permissions.  For now they apply to all users.
5411                if (permissionsState.grantInstallPermission(bp) !=
5412                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5413                    scheduleWriteSettingsLocked();
5414                }
5415                return;
5416            }
5417
5418            if (ps.getInstantApp(userId) && !bp.isInstant()) {
5419                throw new SecurityException("Cannot grant non-ephemeral permission"
5420                        + name + " for package " + packageName);
5421            }
5422
5423            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
5424                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
5425                return;
5426            }
5427
5428            final int result = permissionsState.grantRuntimePermission(bp, userId);
5429            switch (result) {
5430                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
5431                    return;
5432                }
5433
5434                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
5435                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5436                    mHandler.post(new Runnable() {
5437                        @Override
5438                        public void run() {
5439                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
5440                        }
5441                    });
5442                }
5443                break;
5444            }
5445
5446            if (bp.isRuntime()) {
5447                logPermissionGranted(mContext, name, packageName);
5448            }
5449
5450            mOnPermissionChangeListeners.onPermissionsChanged(uid);
5451
5452            // Not critical if that is lost - app has to request again.
5453            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5454        }
5455
5456        // Only need to do this if user is initialized. Otherwise it's a new user
5457        // and there are no processes running as the user yet and there's no need
5458        // to make an expensive call to remount processes for the changed permissions.
5459        if (READ_EXTERNAL_STORAGE.equals(name)
5460                || WRITE_EXTERNAL_STORAGE.equals(name)) {
5461            final long token = Binder.clearCallingIdentity();
5462            try {
5463                if (sUserManager.isInitialized(userId)) {
5464                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
5465                            StorageManagerInternal.class);
5466                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
5467                }
5468            } finally {
5469                Binder.restoreCallingIdentity(token);
5470            }
5471        }
5472    }
5473
5474    @Override
5475    public void revokeRuntimePermission(String packageName, String name, int userId) {
5476        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5477    }
5478
5479    private void revokeRuntimePermission(String packageName, String name, int userId,
5480            boolean overridePolicy) {
5481        if (!sUserManager.exists(userId)) {
5482            Log.e(TAG, "No such user:" + userId);
5483            return;
5484        }
5485
5486        mContext.enforceCallingOrSelfPermission(
5487                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5488                "revokeRuntimePermission");
5489
5490        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5491                true /* requireFullPermission */, true /* checkShell */,
5492                "revokeRuntimePermission");
5493
5494        final int appId;
5495
5496        synchronized (mPackages) {
5497            final PackageParser.Package pkg = mPackages.get(packageName);
5498            if (pkg == null) {
5499                throw new IllegalArgumentException("Unknown package: " + packageName);
5500            }
5501            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5502            if (ps == null
5503                    || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
5504                throw new IllegalArgumentException("Unknown package: " + packageName);
5505            }
5506            final BasePermission bp = mSettings.mPermissions.get(name);
5507            if (bp == null) {
5508                throw new IllegalArgumentException("Unknown permission: " + name);
5509            }
5510
5511            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5512
5513            // If a permission review is required for legacy apps we represent
5514            // their permissions as always granted runtime ones since we need
5515            // to keep the review required permission flag per user while an
5516            // install permission's state is shared across all users.
5517            if (mPermissionReviewRequired
5518                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5519                    && bp.isRuntime()) {
5520                return;
5521            }
5522
5523            final PermissionsState permissionsState = ps.getPermissionsState();
5524
5525            final int flags = permissionsState.getPermissionFlags(name, userId);
5526            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5527                throw new SecurityException("Cannot revoke system fixed permission "
5528                        + name + " for package " + packageName);
5529            }
5530            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5531                throw new SecurityException("Cannot revoke policy fixed permission "
5532                        + name + " for package " + packageName);
5533            }
5534
5535            if (bp.isDevelopment()) {
5536                // Development permissions must be handled specially, since they are not
5537                // normal runtime permissions.  For now they apply to all users.
5538                if (permissionsState.revokeInstallPermission(bp) !=
5539                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5540                    scheduleWriteSettingsLocked();
5541                }
5542                return;
5543            }
5544
5545            if (permissionsState.revokeRuntimePermission(bp, userId) ==
5546                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
5547                return;
5548            }
5549
5550            if (bp.isRuntime()) {
5551                logPermissionRevoked(mContext, name, packageName);
5552            }
5553
5554            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
5555
5556            // Critical, after this call app should never have the permission.
5557            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
5558
5559            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5560        }
5561
5562        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
5563    }
5564
5565    /**
5566     * Get the first event id for the permission.
5567     *
5568     * <p>There are four events for each permission: <ul>
5569     *     <li>Request permission: first id + 0</li>
5570     *     <li>Grant permission: first id + 1</li>
5571     *     <li>Request for permission denied: first id + 2</li>
5572     *     <li>Revoke permission: first id + 3</li>
5573     * </ul></p>
5574     *
5575     * @param name name of the permission
5576     *
5577     * @return The first event id for the permission
5578     */
5579    private static int getBaseEventId(@NonNull String name) {
5580        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
5581
5582        if (eventIdIndex == -1) {
5583            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
5584                    || "user".equals(Build.TYPE)) {
5585                Log.i(TAG, "Unknown permission " + name);
5586
5587                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
5588            } else {
5589                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
5590                //
5591                // Also update
5592                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
5593                // - metrics_constants.proto
5594                throw new IllegalStateException("Unknown permission " + name);
5595            }
5596        }
5597
5598        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
5599    }
5600
5601    /**
5602     * Log that a permission was revoked.
5603     *
5604     * @param context Context of the caller
5605     * @param name name of the permission
5606     * @param packageName package permission if for
5607     */
5608    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
5609            @NonNull String packageName) {
5610        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
5611    }
5612
5613    /**
5614     * Log that a permission request was granted.
5615     *
5616     * @param context Context of the caller
5617     * @param name name of the permission
5618     * @param packageName package permission if for
5619     */
5620    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
5621            @NonNull String packageName) {
5622        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
5623    }
5624
5625    @Override
5626    public void resetRuntimePermissions() {
5627        mContext.enforceCallingOrSelfPermission(
5628                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5629                "revokeRuntimePermission");
5630
5631        int callingUid = Binder.getCallingUid();
5632        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5633            mContext.enforceCallingOrSelfPermission(
5634                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5635                    "resetRuntimePermissions");
5636        }
5637
5638        synchronized (mPackages) {
5639            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
5640            for (int userId : UserManagerService.getInstance().getUserIds()) {
5641                final int packageCount = mPackages.size();
5642                for (int i = 0; i < packageCount; i++) {
5643                    PackageParser.Package pkg = mPackages.valueAt(i);
5644                    if (!(pkg.mExtras instanceof PackageSetting)) {
5645                        continue;
5646                    }
5647                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5648                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5649                }
5650            }
5651        }
5652    }
5653
5654    @Override
5655    public int getPermissionFlags(String name, String packageName, int userId) {
5656        if (!sUserManager.exists(userId)) {
5657            return 0;
5658        }
5659
5660        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
5661
5662        final int callingUid = Binder.getCallingUid();
5663        enforceCrossUserPermission(callingUid, userId,
5664                true /* requireFullPermission */, false /* checkShell */,
5665                "getPermissionFlags");
5666
5667        synchronized (mPackages) {
5668            final PackageParser.Package pkg = mPackages.get(packageName);
5669            if (pkg == null) {
5670                return 0;
5671            }
5672            final BasePermission bp = mSettings.mPermissions.get(name);
5673            if (bp == null) {
5674                return 0;
5675            }
5676            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5677            if (ps == null
5678                    || filterAppAccessLPr(ps, callingUid, userId)) {
5679                return 0;
5680            }
5681            PermissionsState permissionsState = ps.getPermissionsState();
5682            return permissionsState.getPermissionFlags(name, userId);
5683        }
5684    }
5685
5686    @Override
5687    public void updatePermissionFlags(String name, String packageName, int flagMask,
5688            int flagValues, int userId) {
5689        if (!sUserManager.exists(userId)) {
5690            return;
5691        }
5692
5693        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
5694
5695        final int callingUid = Binder.getCallingUid();
5696        enforceCrossUserPermission(callingUid, userId,
5697                true /* requireFullPermission */, true /* checkShell */,
5698                "updatePermissionFlags");
5699
5700        // Only the system can change these flags and nothing else.
5701        if (getCallingUid() != Process.SYSTEM_UID) {
5702            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5703            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5704            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5705            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5706            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
5707        }
5708
5709        synchronized (mPackages) {
5710            final PackageParser.Package pkg = mPackages.get(packageName);
5711            if (pkg == null) {
5712                throw new IllegalArgumentException("Unknown package: " + packageName);
5713            }
5714            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5715            if (ps == null
5716                    || filterAppAccessLPr(ps, callingUid, userId)) {
5717                throw new IllegalArgumentException("Unknown package: " + packageName);
5718            }
5719
5720            final BasePermission bp = mSettings.mPermissions.get(name);
5721            if (bp == null) {
5722                throw new IllegalArgumentException("Unknown permission: " + name);
5723            }
5724
5725            PermissionsState permissionsState = ps.getPermissionsState();
5726
5727            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
5728
5729            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
5730                // Install and runtime permissions are stored in different places,
5731                // so figure out what permission changed and persist the change.
5732                if (permissionsState.getInstallPermissionState(name) != null) {
5733                    scheduleWriteSettingsLocked();
5734                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
5735                        || hadState) {
5736                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5737                }
5738            }
5739        }
5740    }
5741
5742    /**
5743     * Update the permission flags for all packages and runtime permissions of a user in order
5744     * to allow device or profile owner to remove POLICY_FIXED.
5745     */
5746    @Override
5747    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5748        if (!sUserManager.exists(userId)) {
5749            return;
5750        }
5751
5752        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
5753
5754        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5755                true /* requireFullPermission */, true /* checkShell */,
5756                "updatePermissionFlagsForAllApps");
5757
5758        // Only the system can change system fixed flags.
5759        if (getCallingUid() != Process.SYSTEM_UID) {
5760            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5761            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5762        }
5763
5764        synchronized (mPackages) {
5765            boolean changed = false;
5766            final int packageCount = mPackages.size();
5767            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
5768                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
5769                final PackageSetting ps = (PackageSetting) pkg.mExtras;
5770                if (ps == null) {
5771                    continue;
5772                }
5773                PermissionsState permissionsState = ps.getPermissionsState();
5774                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
5775                        userId, flagMask, flagValues);
5776            }
5777            if (changed) {
5778                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5779            }
5780        }
5781    }
5782
5783    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
5784        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
5785                != PackageManager.PERMISSION_GRANTED
5786            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
5787                != PackageManager.PERMISSION_GRANTED) {
5788            throw new SecurityException(message + " requires "
5789                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
5790                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
5791        }
5792    }
5793
5794    @Override
5795    public boolean shouldShowRequestPermissionRationale(String permissionName,
5796            String packageName, int userId) {
5797        if (UserHandle.getCallingUserId() != userId) {
5798            mContext.enforceCallingPermission(
5799                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5800                    "canShowRequestPermissionRationale for user " + userId);
5801        }
5802
5803        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5804        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5805            return false;
5806        }
5807
5808        if (checkPermission(permissionName, packageName, userId)
5809                == PackageManager.PERMISSION_GRANTED) {
5810            return false;
5811        }
5812
5813        final int flags;
5814
5815        final long identity = Binder.clearCallingIdentity();
5816        try {
5817            flags = getPermissionFlags(permissionName,
5818                    packageName, userId);
5819        } finally {
5820            Binder.restoreCallingIdentity(identity);
5821        }
5822
5823        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5824                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5825                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5826
5827        if ((flags & fixedFlags) != 0) {
5828            return false;
5829        }
5830
5831        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5832    }
5833
5834    @Override
5835    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5836        mContext.enforceCallingOrSelfPermission(
5837                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5838                "addOnPermissionsChangeListener");
5839
5840        synchronized (mPackages) {
5841            mOnPermissionChangeListeners.addListenerLocked(listener);
5842        }
5843    }
5844
5845    @Override
5846    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5847        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5848            throw new SecurityException("Instant applications don't have access to this method");
5849        }
5850        synchronized (mPackages) {
5851            mOnPermissionChangeListeners.removeListenerLocked(listener);
5852        }
5853    }
5854
5855    @Override
5856    public boolean isProtectedBroadcast(String actionName) {
5857        // allow instant applications
5858        synchronized (mPackages) {
5859            if (mProtectedBroadcasts.contains(actionName)) {
5860                return true;
5861            } else if (actionName != null) {
5862                // TODO: remove these terrible hacks
5863                if (actionName.startsWith("android.net.netmon.lingerExpired")
5864                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5865                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5866                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5867                    return true;
5868                }
5869            }
5870        }
5871        return false;
5872    }
5873
5874    @Override
5875    public int checkSignatures(String pkg1, String pkg2) {
5876        synchronized (mPackages) {
5877            final PackageParser.Package p1 = mPackages.get(pkg1);
5878            final PackageParser.Package p2 = mPackages.get(pkg2);
5879            if (p1 == null || p1.mExtras == null
5880                    || p2 == null || p2.mExtras == null) {
5881                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5882            }
5883            final int callingUid = Binder.getCallingUid();
5884            final int callingUserId = UserHandle.getUserId(callingUid);
5885            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
5886            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
5887            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
5888                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
5889                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5890            }
5891            return compareSignatures(p1.mSignatures, p2.mSignatures);
5892        }
5893    }
5894
5895    @Override
5896    public int checkUidSignatures(int uid1, int uid2) {
5897        final int callingUid = Binder.getCallingUid();
5898        final int callingUserId = UserHandle.getUserId(callingUid);
5899        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5900        // Map to base uids.
5901        uid1 = UserHandle.getAppId(uid1);
5902        uid2 = UserHandle.getAppId(uid2);
5903        // reader
5904        synchronized (mPackages) {
5905            Signature[] s1;
5906            Signature[] s2;
5907            Object obj = mSettings.getUserIdLPr(uid1);
5908            if (obj != null) {
5909                if (obj instanceof SharedUserSetting) {
5910                    if (isCallerInstantApp) {
5911                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5912                    }
5913                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
5914                } else if (obj instanceof PackageSetting) {
5915                    final PackageSetting ps = (PackageSetting) obj;
5916                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5917                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5918                    }
5919                    s1 = ps.signatures.mSignatures;
5920                } else {
5921                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5922                }
5923            } else {
5924                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5925            }
5926            obj = mSettings.getUserIdLPr(uid2);
5927            if (obj != null) {
5928                if (obj instanceof SharedUserSetting) {
5929                    if (isCallerInstantApp) {
5930                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5931                    }
5932                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
5933                } else if (obj instanceof PackageSetting) {
5934                    final PackageSetting ps = (PackageSetting) obj;
5935                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5936                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5937                    }
5938                    s2 = ps.signatures.mSignatures;
5939                } else {
5940                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5941                }
5942            } else {
5943                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5944            }
5945            return compareSignatures(s1, s2);
5946        }
5947    }
5948
5949    /**
5950     * This method should typically only be used when granting or revoking
5951     * permissions, since the app may immediately restart after this call.
5952     * <p>
5953     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5954     * guard your work against the app being relaunched.
5955     */
5956    private void killUid(int appId, int userId, String reason) {
5957        final long identity = Binder.clearCallingIdentity();
5958        try {
5959            IActivityManager am = ActivityManager.getService();
5960            if (am != null) {
5961                try {
5962                    am.killUid(appId, userId, reason);
5963                } catch (RemoteException e) {
5964                    /* ignore - same process */
5965                }
5966            }
5967        } finally {
5968            Binder.restoreCallingIdentity(identity);
5969        }
5970    }
5971
5972    /**
5973     * Compares two sets of signatures. Returns:
5974     * <br />
5975     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
5976     * <br />
5977     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
5978     * <br />
5979     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
5980     * <br />
5981     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
5982     * <br />
5983     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
5984     */
5985    static int compareSignatures(Signature[] s1, Signature[] s2) {
5986        if (s1 == null) {
5987            return s2 == null
5988                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
5989                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
5990        }
5991
5992        if (s2 == null) {
5993            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
5994        }
5995
5996        if (s1.length != s2.length) {
5997            return PackageManager.SIGNATURE_NO_MATCH;
5998        }
5999
6000        // Since both signature sets are of size 1, we can compare without HashSets.
6001        if (s1.length == 1) {
6002            return s1[0].equals(s2[0]) ?
6003                    PackageManager.SIGNATURE_MATCH :
6004                    PackageManager.SIGNATURE_NO_MATCH;
6005        }
6006
6007        ArraySet<Signature> set1 = new ArraySet<Signature>();
6008        for (Signature sig : s1) {
6009            set1.add(sig);
6010        }
6011        ArraySet<Signature> set2 = new ArraySet<Signature>();
6012        for (Signature sig : s2) {
6013            set2.add(sig);
6014        }
6015        // Make sure s2 contains all signatures in s1.
6016        if (set1.equals(set2)) {
6017            return PackageManager.SIGNATURE_MATCH;
6018        }
6019        return PackageManager.SIGNATURE_NO_MATCH;
6020    }
6021
6022    /**
6023     * If the database version for this type of package (internal storage or
6024     * external storage) is less than the version where package signatures
6025     * were updated, return true.
6026     */
6027    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6028        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6029        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
6030    }
6031
6032    /**
6033     * Used for backward compatibility to make sure any packages with
6034     * certificate chains get upgraded to the new style. {@code existingSigs}
6035     * will be in the old format (since they were stored on disk from before the
6036     * system upgrade) and {@code scannedSigs} will be in the newer format.
6037     */
6038    private int compareSignaturesCompat(PackageSignatures existingSigs,
6039            PackageParser.Package scannedPkg) {
6040        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
6041            return PackageManager.SIGNATURE_NO_MATCH;
6042        }
6043
6044        ArraySet<Signature> existingSet = new ArraySet<Signature>();
6045        for (Signature sig : existingSigs.mSignatures) {
6046            existingSet.add(sig);
6047        }
6048        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
6049        for (Signature sig : scannedPkg.mSignatures) {
6050            try {
6051                Signature[] chainSignatures = sig.getChainSignatures();
6052                for (Signature chainSig : chainSignatures) {
6053                    scannedCompatSet.add(chainSig);
6054                }
6055            } catch (CertificateEncodingException e) {
6056                scannedCompatSet.add(sig);
6057            }
6058        }
6059        /*
6060         * Make sure the expanded scanned set contains all signatures in the
6061         * existing one.
6062         */
6063        if (scannedCompatSet.equals(existingSet)) {
6064            // Migrate the old signatures to the new scheme.
6065            existingSigs.assignSignatures(scannedPkg.mSignatures);
6066            // The new KeySets will be re-added later in the scanning process.
6067            synchronized (mPackages) {
6068                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
6069            }
6070            return PackageManager.SIGNATURE_MATCH;
6071        }
6072        return PackageManager.SIGNATURE_NO_MATCH;
6073    }
6074
6075    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6076        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6077        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
6078    }
6079
6080    private int compareSignaturesRecover(PackageSignatures existingSigs,
6081            PackageParser.Package scannedPkg) {
6082        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
6083            return PackageManager.SIGNATURE_NO_MATCH;
6084        }
6085
6086        String msg = null;
6087        try {
6088            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
6089                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
6090                        + scannedPkg.packageName);
6091                return PackageManager.SIGNATURE_MATCH;
6092            }
6093        } catch (CertificateException e) {
6094            msg = e.getMessage();
6095        }
6096
6097        logCriticalInfo(Log.INFO,
6098                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
6099        return PackageManager.SIGNATURE_NO_MATCH;
6100    }
6101
6102    @Override
6103    public List<String> getAllPackages() {
6104        final int callingUid = Binder.getCallingUid();
6105        final int callingUserId = UserHandle.getUserId(callingUid);
6106        synchronized (mPackages) {
6107            if (canViewInstantApps(callingUid, callingUserId)) {
6108                return new ArrayList<String>(mPackages.keySet());
6109            }
6110            final String instantAppPkgName = getInstantAppPackageName(callingUid);
6111            final List<String> result = new ArrayList<>();
6112            if (instantAppPkgName != null) {
6113                // caller is an instant application; filter unexposed applications
6114                for (PackageParser.Package pkg : mPackages.values()) {
6115                    if (!pkg.visibleToInstantApps) {
6116                        continue;
6117                    }
6118                    result.add(pkg.packageName);
6119                }
6120            } else {
6121                // caller is a normal application; filter instant applications
6122                for (PackageParser.Package pkg : mPackages.values()) {
6123                    final PackageSetting ps =
6124                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
6125                    if (ps != null
6126                            && ps.getInstantApp(callingUserId)
6127                            && !mInstantAppRegistry.isInstantAccessGranted(
6128                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
6129                        continue;
6130                    }
6131                    result.add(pkg.packageName);
6132                }
6133            }
6134            return result;
6135        }
6136    }
6137
6138    @Override
6139    public String[] getPackagesForUid(int uid) {
6140        final int callingUid = Binder.getCallingUid();
6141        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
6142        final int userId = UserHandle.getUserId(uid);
6143        uid = UserHandle.getAppId(uid);
6144        // reader
6145        synchronized (mPackages) {
6146            Object obj = mSettings.getUserIdLPr(uid);
6147            if (obj instanceof SharedUserSetting) {
6148                if (isCallerInstantApp) {
6149                    return null;
6150                }
6151                final SharedUserSetting sus = (SharedUserSetting) obj;
6152                final int N = sus.packages.size();
6153                String[] res = new String[N];
6154                final Iterator<PackageSetting> it = sus.packages.iterator();
6155                int i = 0;
6156                while (it.hasNext()) {
6157                    PackageSetting ps = it.next();
6158                    if (ps.getInstalled(userId)) {
6159                        res[i++] = ps.name;
6160                    } else {
6161                        res = ArrayUtils.removeElement(String.class, res, res[i]);
6162                    }
6163                }
6164                return res;
6165            } else if (obj instanceof PackageSetting) {
6166                final PackageSetting ps = (PackageSetting) obj;
6167                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
6168                    return new String[]{ps.name};
6169                }
6170            }
6171        }
6172        return null;
6173    }
6174
6175    @Override
6176    public String getNameForUid(int uid) {
6177        final int callingUid = Binder.getCallingUid();
6178        if (getInstantAppPackageName(callingUid) != null) {
6179            return null;
6180        }
6181        synchronized (mPackages) {
6182            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6183            if (obj instanceof SharedUserSetting) {
6184                final SharedUserSetting sus = (SharedUserSetting) obj;
6185                return sus.name + ":" + sus.userId;
6186            } else if (obj instanceof PackageSetting) {
6187                final PackageSetting ps = (PackageSetting) obj;
6188                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6189                    return null;
6190                }
6191                return ps.name;
6192            }
6193        }
6194        return null;
6195    }
6196
6197    @Override
6198    public int getUidForSharedUser(String sharedUserName) {
6199        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6200            return -1;
6201        }
6202        if (sharedUserName == null) {
6203            return -1;
6204        }
6205        // reader
6206        synchronized (mPackages) {
6207            SharedUserSetting suid;
6208            try {
6209                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
6210                if (suid != null) {
6211                    return suid.userId;
6212                }
6213            } catch (PackageManagerException ignore) {
6214                // can't happen, but, still need to catch it
6215            }
6216            return -1;
6217        }
6218    }
6219
6220    @Override
6221    public int getFlagsForUid(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.pkgFlags;
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.pkgFlags;
6237            }
6238        }
6239        return 0;
6240    }
6241
6242    @Override
6243    public int getPrivateFlagsForUid(int uid) {
6244        final int callingUid = Binder.getCallingUid();
6245        if (getInstantAppPackageName(callingUid) != null) {
6246            return 0;
6247        }
6248        synchronized (mPackages) {
6249            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6250            if (obj instanceof SharedUserSetting) {
6251                final SharedUserSetting sus = (SharedUserSetting) obj;
6252                return sus.pkgPrivateFlags;
6253            } else if (obj instanceof PackageSetting) {
6254                final PackageSetting ps = (PackageSetting) obj;
6255                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6256                    return 0;
6257                }
6258                return ps.pkgPrivateFlags;
6259            }
6260        }
6261        return 0;
6262    }
6263
6264    @Override
6265    public boolean isUidPrivileged(int uid) {
6266        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6267            return false;
6268        }
6269        uid = UserHandle.getAppId(uid);
6270        // reader
6271        synchronized (mPackages) {
6272            Object obj = mSettings.getUserIdLPr(uid);
6273            if (obj instanceof SharedUserSetting) {
6274                final SharedUserSetting sus = (SharedUserSetting) obj;
6275                final Iterator<PackageSetting> it = sus.packages.iterator();
6276                while (it.hasNext()) {
6277                    if (it.next().isPrivileged()) {
6278                        return true;
6279                    }
6280                }
6281            } else if (obj instanceof PackageSetting) {
6282                final PackageSetting ps = (PackageSetting) obj;
6283                return ps.isPrivileged();
6284            }
6285        }
6286        return false;
6287    }
6288
6289    @Override
6290    public String[] getAppOpPermissionPackages(String permissionName) {
6291        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6292            return null;
6293        }
6294        synchronized (mPackages) {
6295            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
6296            if (pkgs == null) {
6297                return null;
6298            }
6299            return pkgs.toArray(new String[pkgs.size()]);
6300        }
6301    }
6302
6303    @Override
6304    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
6305            int flags, int userId) {
6306        return resolveIntentInternal(
6307                intent, resolvedType, flags, userId, false /*includeInstantApps*/);
6308    }
6309
6310    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
6311            int flags, int userId, boolean resolveForStart) {
6312        try {
6313            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
6314
6315            if (!sUserManager.exists(userId)) return null;
6316            final int callingUid = Binder.getCallingUid();
6317            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
6318            enforceCrossUserPermission(callingUid, userId,
6319                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
6320
6321            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6322            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
6323                    flags, callingUid, userId, resolveForStart);
6324            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6325
6326            final ResolveInfo bestChoice =
6327                    chooseBestActivity(intent, resolvedType, flags, query, userId);
6328            return bestChoice;
6329        } finally {
6330            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6331        }
6332    }
6333
6334    @Override
6335    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
6336        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
6337            throw new SecurityException(
6338                    "findPersistentPreferredActivity can only be run by the system");
6339        }
6340        if (!sUserManager.exists(userId)) {
6341            return null;
6342        }
6343        final int callingUid = Binder.getCallingUid();
6344        intent = updateIntentForResolve(intent);
6345        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
6346        final int flags = updateFlagsForResolve(
6347                0, userId, intent, callingUid, false /*includeInstantApps*/);
6348        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6349                userId);
6350        synchronized (mPackages) {
6351            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
6352                    userId);
6353        }
6354    }
6355
6356    @Override
6357    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
6358            IntentFilter filter, int match, ComponentName activity) {
6359        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6360            return;
6361        }
6362        final int userId = UserHandle.getCallingUserId();
6363        if (DEBUG_PREFERRED) {
6364            Log.v(TAG, "setLastChosenActivity intent=" + intent
6365                + " resolvedType=" + resolvedType
6366                + " flags=" + flags
6367                + " filter=" + filter
6368                + " match=" + match
6369                + " activity=" + activity);
6370            filter.dump(new PrintStreamPrinter(System.out), "    ");
6371        }
6372        intent.setComponent(null);
6373        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6374                userId);
6375        // Find any earlier preferred or last chosen entries and nuke them
6376        findPreferredActivity(intent, resolvedType,
6377                flags, query, 0, false, true, false, userId);
6378        // Add the new activity as the last chosen for this filter
6379        addPreferredActivityInternal(filter, match, null, activity, false, userId,
6380                "Setting last chosen");
6381    }
6382
6383    @Override
6384    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
6385        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6386            return null;
6387        }
6388        final int userId = UserHandle.getCallingUserId();
6389        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
6390        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6391                userId);
6392        return findPreferredActivity(intent, resolvedType, flags, query, 0,
6393                false, false, false, userId);
6394    }
6395
6396    /**
6397     * Returns whether or not instant apps have been disabled remotely.
6398     */
6399    private boolean isEphemeralDisabled() {
6400        return mEphemeralAppsDisabled;
6401    }
6402
6403    private boolean isInstantAppAllowed(
6404            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
6405            boolean skipPackageCheck) {
6406        if (mInstantAppResolverConnection == null) {
6407            return false;
6408        }
6409        if (mInstantAppInstallerActivity == null) {
6410            return false;
6411        }
6412        if (intent.getComponent() != null) {
6413            return false;
6414        }
6415        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
6416            return false;
6417        }
6418        if (!skipPackageCheck && intent.getPackage() != null) {
6419            return false;
6420        }
6421        final boolean isWebUri = hasWebURI(intent);
6422        if (!isWebUri || intent.getData().getHost() == null) {
6423            return false;
6424        }
6425        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
6426        // Or if there's already an ephemeral app installed that handles the action
6427        synchronized (mPackages) {
6428            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
6429            for (int n = 0; n < count; n++) {
6430                final ResolveInfo info = resolvedActivities.get(n);
6431                final String packageName = info.activityInfo.packageName;
6432                final PackageSetting ps = mSettings.mPackages.get(packageName);
6433                if (ps != null) {
6434                    // only check domain verification status if the app is not a browser
6435                    if (!info.handleAllWebDataURI) {
6436                        // Try to get the status from User settings first
6437                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6438                        final int status = (int) (packedStatus >> 32);
6439                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
6440                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6441                            if (DEBUG_EPHEMERAL) {
6442                                Slog.v(TAG, "DENY instant app;"
6443                                    + " pkg: " + packageName + ", status: " + status);
6444                            }
6445                            return false;
6446                        }
6447                    }
6448                    if (ps.getInstantApp(userId)) {
6449                        if (DEBUG_EPHEMERAL) {
6450                            Slog.v(TAG, "DENY instant app installed;"
6451                                    + " pkg: " + packageName);
6452                        }
6453                        return false;
6454                    }
6455                }
6456            }
6457        }
6458        // We've exhausted all ways to deny ephemeral application; let the system look for them.
6459        return true;
6460    }
6461
6462    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
6463            Intent origIntent, String resolvedType, String callingPackage,
6464            Bundle verificationBundle, int userId) {
6465        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
6466                new InstantAppRequest(responseObj, origIntent, resolvedType,
6467                        callingPackage, userId, verificationBundle));
6468        mHandler.sendMessage(msg);
6469    }
6470
6471    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
6472            int flags, List<ResolveInfo> query, int userId) {
6473        if (query != null) {
6474            final int N = query.size();
6475            if (N == 1) {
6476                return query.get(0);
6477            } else if (N > 1) {
6478                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
6479                // If there is more than one activity with the same priority,
6480                // then let the user decide between them.
6481                ResolveInfo r0 = query.get(0);
6482                ResolveInfo r1 = query.get(1);
6483                if (DEBUG_INTENT_MATCHING || debug) {
6484                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
6485                            + r1.activityInfo.name + "=" + r1.priority);
6486                }
6487                // If the first activity has a higher priority, or a different
6488                // default, then it is always desirable to pick it.
6489                if (r0.priority != r1.priority
6490                        || r0.preferredOrder != r1.preferredOrder
6491                        || r0.isDefault != r1.isDefault) {
6492                    return query.get(0);
6493                }
6494                // If we have saved a preference for a preferred activity for
6495                // this Intent, use that.
6496                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
6497                        flags, query, r0.priority, true, false, debug, userId);
6498                if (ri != null) {
6499                    return ri;
6500                }
6501                // If we have an ephemeral app, use it
6502                for (int i = 0; i < N; i++) {
6503                    ri = query.get(i);
6504                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
6505                        final String packageName = ri.activityInfo.packageName;
6506                        final PackageSetting ps = mSettings.mPackages.get(packageName);
6507                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6508                        final int status = (int)(packedStatus >> 32);
6509                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6510                            return ri;
6511                        }
6512                    }
6513                }
6514                ri = new ResolveInfo(mResolveInfo);
6515                ri.activityInfo = new ActivityInfo(ri.activityInfo);
6516                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6517                // If all of the options come from the same package, show the application's
6518                // label and icon instead of the generic resolver's.
6519                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6520                // and then throw away the ResolveInfo itself, meaning that the caller loses
6521                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6522                // a fallback for this case; we only set the target package's resources on
6523                // the ResolveInfo, not the ActivityInfo.
6524                final String intentPackage = intent.getPackage();
6525                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6526                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6527                    ri.resolvePackageName = intentPackage;
6528                    if (userNeedsBadging(userId)) {
6529                        ri.noResourceId = true;
6530                    } else {
6531                        ri.icon = appi.icon;
6532                    }
6533                    ri.iconResourceId = appi.icon;
6534                    ri.labelRes = appi.labelRes;
6535                }
6536                ri.activityInfo.applicationInfo = new ApplicationInfo(
6537                        ri.activityInfo.applicationInfo);
6538                if (userId != 0) {
6539                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6540                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6541                }
6542                // Make sure that the resolver is displayable in car mode
6543                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6544                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6545                return ri;
6546            }
6547        }
6548        return null;
6549    }
6550
6551    /**
6552     * Return true if the given list is not empty and all of its contents have
6553     * an activityInfo with the given package name.
6554     */
6555    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6556        if (ArrayUtils.isEmpty(list)) {
6557            return false;
6558        }
6559        for (int i = 0, N = list.size(); i < N; i++) {
6560            final ResolveInfo ri = list.get(i);
6561            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6562            if (ai == null || !packageName.equals(ai.packageName)) {
6563                return false;
6564            }
6565        }
6566        return true;
6567    }
6568
6569    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6570            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6571        final int N = query.size();
6572        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6573                .get(userId);
6574        // Get the list of persistent preferred activities that handle the intent
6575        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6576        List<PersistentPreferredActivity> pprefs = ppir != null
6577                ? ppir.queryIntent(intent, resolvedType,
6578                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6579                        userId)
6580                : null;
6581        if (pprefs != null && pprefs.size() > 0) {
6582            final int M = pprefs.size();
6583            for (int i=0; i<M; i++) {
6584                final PersistentPreferredActivity ppa = pprefs.get(i);
6585                if (DEBUG_PREFERRED || debug) {
6586                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6587                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6588                            + "\n  component=" + ppa.mComponent);
6589                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6590                }
6591                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6592                        flags | MATCH_DISABLED_COMPONENTS, userId);
6593                if (DEBUG_PREFERRED || debug) {
6594                    Slog.v(TAG, "Found persistent preferred activity:");
6595                    if (ai != null) {
6596                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6597                    } else {
6598                        Slog.v(TAG, "  null");
6599                    }
6600                }
6601                if (ai == null) {
6602                    // This previously registered persistent preferred activity
6603                    // component is no longer known. Ignore it and do NOT remove it.
6604                    continue;
6605                }
6606                for (int j=0; j<N; j++) {
6607                    final ResolveInfo ri = query.get(j);
6608                    if (!ri.activityInfo.applicationInfo.packageName
6609                            .equals(ai.applicationInfo.packageName)) {
6610                        continue;
6611                    }
6612                    if (!ri.activityInfo.name.equals(ai.name)) {
6613                        continue;
6614                    }
6615                    //  Found a persistent preference that can handle the intent.
6616                    if (DEBUG_PREFERRED || debug) {
6617                        Slog.v(TAG, "Returning persistent preferred activity: " +
6618                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6619                    }
6620                    return ri;
6621                }
6622            }
6623        }
6624        return null;
6625    }
6626
6627    // TODO: handle preferred activities missing while user has amnesia
6628    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6629            List<ResolveInfo> query, int priority, boolean always,
6630            boolean removeMatches, boolean debug, int userId) {
6631        if (!sUserManager.exists(userId)) return null;
6632        final int callingUid = Binder.getCallingUid();
6633        flags = updateFlagsForResolve(
6634                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6635        intent = updateIntentForResolve(intent);
6636        // writer
6637        synchronized (mPackages) {
6638            // Try to find a matching persistent preferred activity.
6639            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6640                    debug, userId);
6641
6642            // If a persistent preferred activity matched, use it.
6643            if (pri != null) {
6644                return pri;
6645            }
6646
6647            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6648            // Get the list of preferred activities that handle the intent
6649            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6650            List<PreferredActivity> prefs = pir != null
6651                    ? pir.queryIntent(intent, resolvedType,
6652                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6653                            userId)
6654                    : null;
6655            if (prefs != null && prefs.size() > 0) {
6656                boolean changed = false;
6657                try {
6658                    // First figure out how good the original match set is.
6659                    // We will only allow preferred activities that came
6660                    // from the same match quality.
6661                    int match = 0;
6662
6663                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6664
6665                    final int N = query.size();
6666                    for (int j=0; j<N; j++) {
6667                        final ResolveInfo ri = query.get(j);
6668                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6669                                + ": 0x" + Integer.toHexString(match));
6670                        if (ri.match > match) {
6671                            match = ri.match;
6672                        }
6673                    }
6674
6675                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6676                            + Integer.toHexString(match));
6677
6678                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6679                    final int M = prefs.size();
6680                    for (int i=0; i<M; i++) {
6681                        final PreferredActivity pa = prefs.get(i);
6682                        if (DEBUG_PREFERRED || debug) {
6683                            Slog.v(TAG, "Checking PreferredActivity ds="
6684                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6685                                    + "\n  component=" + pa.mPref.mComponent);
6686                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6687                        }
6688                        if (pa.mPref.mMatch != match) {
6689                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6690                                    + Integer.toHexString(pa.mPref.mMatch));
6691                            continue;
6692                        }
6693                        // If it's not an "always" type preferred activity and that's what we're
6694                        // looking for, skip it.
6695                        if (always && !pa.mPref.mAlways) {
6696                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6697                            continue;
6698                        }
6699                        final ActivityInfo ai = getActivityInfo(
6700                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6701                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6702                                userId);
6703                        if (DEBUG_PREFERRED || debug) {
6704                            Slog.v(TAG, "Found preferred activity:");
6705                            if (ai != null) {
6706                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6707                            } else {
6708                                Slog.v(TAG, "  null");
6709                            }
6710                        }
6711                        if (ai == null) {
6712                            // This previously registered preferred activity
6713                            // component is no longer known.  Most likely an update
6714                            // to the app was installed and in the new version this
6715                            // component no longer exists.  Clean it up by removing
6716                            // it from the preferred activities list, and skip it.
6717                            Slog.w(TAG, "Removing dangling preferred activity: "
6718                                    + pa.mPref.mComponent);
6719                            pir.removeFilter(pa);
6720                            changed = true;
6721                            continue;
6722                        }
6723                        for (int j=0; j<N; j++) {
6724                            final ResolveInfo ri = query.get(j);
6725                            if (!ri.activityInfo.applicationInfo.packageName
6726                                    .equals(ai.applicationInfo.packageName)) {
6727                                continue;
6728                            }
6729                            if (!ri.activityInfo.name.equals(ai.name)) {
6730                                continue;
6731                            }
6732
6733                            if (removeMatches) {
6734                                pir.removeFilter(pa);
6735                                changed = true;
6736                                if (DEBUG_PREFERRED) {
6737                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6738                                }
6739                                break;
6740                            }
6741
6742                            // Okay we found a previously set preferred or last chosen app.
6743                            // If the result set is different from when this
6744                            // was created, we need to clear it and re-ask the
6745                            // user their preference, if we're looking for an "always" type entry.
6746                            if (always && !pa.mPref.sameSet(query)) {
6747                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
6748                                        + intent + " type " + resolvedType);
6749                                if (DEBUG_PREFERRED) {
6750                                    Slog.v(TAG, "Removing preferred activity since set changed "
6751                                            + pa.mPref.mComponent);
6752                                }
6753                                pir.removeFilter(pa);
6754                                // Re-add the filter as a "last chosen" entry (!always)
6755                                PreferredActivity lastChosen = new PreferredActivity(
6756                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6757                                pir.addFilter(lastChosen);
6758                                changed = true;
6759                                return null;
6760                            }
6761
6762                            // Yay! Either the set matched or we're looking for the last chosen
6763                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6764                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6765                            return ri;
6766                        }
6767                    }
6768                } finally {
6769                    if (changed) {
6770                        if (DEBUG_PREFERRED) {
6771                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6772                        }
6773                        scheduleWritePackageRestrictionsLocked(userId);
6774                    }
6775                }
6776            }
6777        }
6778        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6779        return null;
6780    }
6781
6782    /*
6783     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6784     */
6785    @Override
6786    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6787            int targetUserId) {
6788        mContext.enforceCallingOrSelfPermission(
6789                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6790        List<CrossProfileIntentFilter> matches =
6791                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6792        if (matches != null) {
6793            int size = matches.size();
6794            for (int i = 0; i < size; i++) {
6795                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6796            }
6797        }
6798        if (hasWebURI(intent)) {
6799            // cross-profile app linking works only towards the parent.
6800            final int callingUid = Binder.getCallingUid();
6801            final UserInfo parent = getProfileParent(sourceUserId);
6802            synchronized(mPackages) {
6803                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
6804                        false /*includeInstantApps*/);
6805                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6806                        intent, resolvedType, flags, sourceUserId, parent.id);
6807                return xpDomainInfo != null;
6808            }
6809        }
6810        return false;
6811    }
6812
6813    private UserInfo getProfileParent(int userId) {
6814        final long identity = Binder.clearCallingIdentity();
6815        try {
6816            return sUserManager.getProfileParent(userId);
6817        } finally {
6818            Binder.restoreCallingIdentity(identity);
6819        }
6820    }
6821
6822    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6823            String resolvedType, int userId) {
6824        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6825        if (resolver != null) {
6826            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6827        }
6828        return null;
6829    }
6830
6831    @Override
6832    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6833            String resolvedType, int flags, int userId) {
6834        try {
6835            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6836
6837            return new ParceledListSlice<>(
6838                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6839        } finally {
6840            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6841        }
6842    }
6843
6844    /**
6845     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6846     * instant, returns {@code null}.
6847     */
6848    private String getInstantAppPackageName(int callingUid) {
6849        synchronized (mPackages) {
6850            // If the caller is an isolated app use the owner's uid for the lookup.
6851            if (Process.isIsolated(callingUid)) {
6852                callingUid = mIsolatedOwners.get(callingUid);
6853            }
6854            final int appId = UserHandle.getAppId(callingUid);
6855            final Object obj = mSettings.getUserIdLPr(appId);
6856            if (obj instanceof PackageSetting) {
6857                final PackageSetting ps = (PackageSetting) obj;
6858                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6859                return isInstantApp ? ps.pkg.packageName : null;
6860            }
6861        }
6862        return null;
6863    }
6864
6865    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6866            String resolvedType, int flags, int userId) {
6867        return queryIntentActivitiesInternal(
6868                intent, resolvedType, flags, Binder.getCallingUid(), userId, false);
6869    }
6870
6871    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6872            String resolvedType, int flags, int filterCallingUid, int userId,
6873            boolean resolveForStart) {
6874        if (!sUserManager.exists(userId)) return Collections.emptyList();
6875        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
6876        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6877                false /* requireFullPermission */, false /* checkShell */,
6878                "query intent activities");
6879        final String pkgName = intent.getPackage();
6880        ComponentName comp = intent.getComponent();
6881        if (comp == null) {
6882            if (intent.getSelector() != null) {
6883                intent = intent.getSelector();
6884                comp = intent.getComponent();
6885            }
6886        }
6887
6888        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
6889                comp != null || pkgName != null /*onlyExposedExplicitly*/);
6890        if (comp != null) {
6891            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6892            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6893            if (ai != null) {
6894                // When specifying an explicit component, we prevent the activity from being
6895                // used when either 1) the calling package is normal and the activity is within
6896                // an ephemeral application or 2) the calling package is ephemeral and the
6897                // activity is not visible to ephemeral applications.
6898                final boolean matchInstantApp =
6899                        (flags & PackageManager.MATCH_INSTANT) != 0;
6900                final boolean matchVisibleToInstantAppOnly =
6901                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6902                final boolean matchExplicitlyVisibleOnly =
6903                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
6904                final boolean isCallerInstantApp =
6905                        instantAppPkgName != null;
6906                final boolean isTargetSameInstantApp =
6907                        comp.getPackageName().equals(instantAppPkgName);
6908                final boolean isTargetInstantApp =
6909                        (ai.applicationInfo.privateFlags
6910                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6911                final boolean isTargetVisibleToInstantApp =
6912                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
6913                final boolean isTargetExplicitlyVisibleToInstantApp =
6914                        isTargetVisibleToInstantApp
6915                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
6916                final boolean isTargetHiddenFromInstantApp =
6917                        !isTargetVisibleToInstantApp
6918                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
6919                final boolean blockResolution =
6920                        !isTargetSameInstantApp
6921                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6922                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6923                                        && isTargetHiddenFromInstantApp));
6924                if (!blockResolution) {
6925                    final ResolveInfo ri = new ResolveInfo();
6926                    ri.activityInfo = ai;
6927                    list.add(ri);
6928                }
6929            }
6930            return applyPostResolutionFilter(list, instantAppPkgName);
6931        }
6932
6933        // reader
6934        boolean sortResult = false;
6935        boolean addEphemeral = false;
6936        List<ResolveInfo> result;
6937        final boolean ephemeralDisabled = isEphemeralDisabled();
6938        synchronized (mPackages) {
6939            if (pkgName == null) {
6940                List<CrossProfileIntentFilter> matchingFilters =
6941                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6942                // Check for results that need to skip the current profile.
6943                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6944                        resolvedType, flags, userId);
6945                if (xpResolveInfo != null) {
6946                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6947                    xpResult.add(xpResolveInfo);
6948                    return applyPostResolutionFilter(
6949                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName);
6950                }
6951
6952                // Check for results in the current profile.
6953                result = filterIfNotSystemUser(mActivities.queryIntent(
6954                        intent, resolvedType, flags, userId), userId);
6955                addEphemeral = !ephemeralDisabled
6956                        && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/);
6957                // Check for cross profile results.
6958                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6959                xpResolveInfo = queryCrossProfileIntents(
6960                        matchingFilters, intent, resolvedType, flags, userId,
6961                        hasNonNegativePriorityResult);
6962                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6963                    boolean isVisibleToUser = filterIfNotSystemUser(
6964                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6965                    if (isVisibleToUser) {
6966                        result.add(xpResolveInfo);
6967                        sortResult = true;
6968                    }
6969                }
6970                if (hasWebURI(intent)) {
6971                    CrossProfileDomainInfo xpDomainInfo = null;
6972                    final UserInfo parent = getProfileParent(userId);
6973                    if (parent != null) {
6974                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6975                                flags, userId, parent.id);
6976                    }
6977                    if (xpDomainInfo != null) {
6978                        if (xpResolveInfo != null) {
6979                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6980                            // in the result.
6981                            result.remove(xpResolveInfo);
6982                        }
6983                        if (result.size() == 0 && !addEphemeral) {
6984                            // No result in current profile, but found candidate in parent user.
6985                            // And we are not going to add emphemeral app, so we can return the
6986                            // result straight away.
6987                            result.add(xpDomainInfo.resolveInfo);
6988                            return applyPostResolutionFilter(result, instantAppPkgName);
6989                        }
6990                    } else if (result.size() <= 1 && !addEphemeral) {
6991                        // No result in parent user and <= 1 result in current profile, and we
6992                        // are not going to add emphemeral app, so we can return the result without
6993                        // further processing.
6994                        return applyPostResolutionFilter(result, instantAppPkgName);
6995                    }
6996                    // We have more than one candidate (combining results from current and parent
6997                    // profile), so we need filtering and sorting.
6998                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6999                            intent, flags, result, xpDomainInfo, userId);
7000                    sortResult = true;
7001                }
7002            } else {
7003                final PackageParser.Package pkg = mPackages.get(pkgName);
7004                result = null;
7005                if (pkg != null) {
7006                    result = filterIfNotSystemUser(
7007                            mActivities.queryIntentForPackage(
7008                                    intent, resolvedType, flags, pkg.activities, userId),
7009                            userId);
7010                }
7011                if (result == null || result.size() == 0) {
7012                    // the caller wants to resolve for a particular package; however, there
7013                    // were no installed results, so, try to find an ephemeral result
7014                    addEphemeral = !ephemeralDisabled
7015                            && isInstantAppAllowed(
7016                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
7017                    if (result == null) {
7018                        result = new ArrayList<>();
7019                    }
7020                }
7021            }
7022        }
7023        if (addEphemeral) {
7024            result = maybeAddInstantAppInstaller(result, intent, resolvedType, flags, userId);
7025        }
7026        if (sortResult) {
7027            Collections.sort(result, mResolvePrioritySorter);
7028        }
7029        return applyPostResolutionFilter(result, instantAppPkgName);
7030    }
7031
7032    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
7033            String resolvedType, int flags, int userId) {
7034        // first, check to see if we've got an instant app already installed
7035        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
7036        ResolveInfo localInstantApp = null;
7037        boolean blockResolution = false;
7038        if (!alreadyResolvedLocally) {
7039            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
7040                    flags
7041                        | PackageManager.GET_RESOLVED_FILTER
7042                        | PackageManager.MATCH_INSTANT
7043                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
7044                    userId);
7045            for (int i = instantApps.size() - 1; i >= 0; --i) {
7046                final ResolveInfo info = instantApps.get(i);
7047                final String packageName = info.activityInfo.packageName;
7048                final PackageSetting ps = mSettings.mPackages.get(packageName);
7049                if (ps.getInstantApp(userId)) {
7050                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7051                    final int status = (int)(packedStatus >> 32);
7052                    final int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7053                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7054                        // there's a local instant application installed, but, the user has
7055                        // chosen to never use it; skip resolution and don't acknowledge
7056                        // an instant application is even available
7057                        if (DEBUG_EPHEMERAL) {
7058                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
7059                        }
7060                        blockResolution = true;
7061                        break;
7062                    } else {
7063                        // we have a locally installed instant application; skip resolution
7064                        // but acknowledge there's an instant application available
7065                        if (DEBUG_EPHEMERAL) {
7066                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
7067                        }
7068                        localInstantApp = info;
7069                        break;
7070                    }
7071                }
7072            }
7073        }
7074        // no app installed, let's see if one's available
7075        AuxiliaryResolveInfo auxiliaryResponse = null;
7076        if (!blockResolution) {
7077            if (localInstantApp == null) {
7078                // we don't have an instant app locally, resolve externally
7079                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
7080                final InstantAppRequest requestObject = new InstantAppRequest(
7081                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
7082                        null /*callingPackage*/, userId, null /*verificationBundle*/);
7083                auxiliaryResponse =
7084                        InstantAppResolver.doInstantAppResolutionPhaseOne(
7085                                mContext, mInstantAppResolverConnection, requestObject);
7086                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7087            } else {
7088                // we have an instant application locally, but, we can't admit that since
7089                // callers shouldn't be able to determine prior browsing. create a dummy
7090                // auxiliary response so the downstream code behaves as if there's an
7091                // instant application available externally. when it comes time to start
7092                // the instant application, we'll do the right thing.
7093                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
7094                auxiliaryResponse = new AuxiliaryResolveInfo(
7095                        ai.packageName, null /*splitName*/, ai.versionCode, null /*failureIntent*/);
7096            }
7097        }
7098        if (auxiliaryResponse != null) {
7099            if (DEBUG_EPHEMERAL) {
7100                Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7101            }
7102            final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
7103            final PackageSetting ps =
7104                    mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
7105            if (ps != null) {
7106                ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
7107                        mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
7108                ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
7109                ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
7110                // make sure this resolver is the default
7111                ephemeralInstaller.isDefault = true;
7112                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7113                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7114                // add a non-generic filter
7115                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
7116                ephemeralInstaller.filter.addDataPath(
7117                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
7118                ephemeralInstaller.isInstantAppAvailable = true;
7119                result.add(ephemeralInstaller);
7120            }
7121        }
7122        return result;
7123    }
7124
7125    private static class CrossProfileDomainInfo {
7126        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
7127        ResolveInfo resolveInfo;
7128        /* Best domain verification status of the activities found in the other profile */
7129        int bestDomainVerificationStatus;
7130    }
7131
7132    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
7133            String resolvedType, int flags, int sourceUserId, int parentUserId) {
7134        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
7135                sourceUserId)) {
7136            return null;
7137        }
7138        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7139                resolvedType, flags, parentUserId);
7140
7141        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
7142            return null;
7143        }
7144        CrossProfileDomainInfo result = null;
7145        int size = resultTargetUser.size();
7146        for (int i = 0; i < size; i++) {
7147            ResolveInfo riTargetUser = resultTargetUser.get(i);
7148            // Intent filter verification is only for filters that specify a host. So don't return
7149            // those that handle all web uris.
7150            if (riTargetUser.handleAllWebDataURI) {
7151                continue;
7152            }
7153            String packageName = riTargetUser.activityInfo.packageName;
7154            PackageSetting ps = mSettings.mPackages.get(packageName);
7155            if (ps == null) {
7156                continue;
7157            }
7158            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
7159            int status = (int)(verificationState >> 32);
7160            if (result == null) {
7161                result = new CrossProfileDomainInfo();
7162                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
7163                        sourceUserId, parentUserId);
7164                result.bestDomainVerificationStatus = status;
7165            } else {
7166                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
7167                        result.bestDomainVerificationStatus);
7168            }
7169        }
7170        // Don't consider matches with status NEVER across profiles.
7171        if (result != null && result.bestDomainVerificationStatus
7172                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7173            return null;
7174        }
7175        return result;
7176    }
7177
7178    /**
7179     * Verification statuses are ordered from the worse to the best, except for
7180     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
7181     */
7182    private int bestDomainVerificationStatus(int status1, int status2) {
7183        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7184            return status2;
7185        }
7186        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7187            return status1;
7188        }
7189        return (int) MathUtils.max(status1, status2);
7190    }
7191
7192    private boolean isUserEnabled(int userId) {
7193        long callingId = Binder.clearCallingIdentity();
7194        try {
7195            UserInfo userInfo = sUserManager.getUserInfo(userId);
7196            return userInfo != null && userInfo.isEnabled();
7197        } finally {
7198            Binder.restoreCallingIdentity(callingId);
7199        }
7200    }
7201
7202    /**
7203     * Filter out activities with systemUserOnly flag set, when current user is not System.
7204     *
7205     * @return filtered list
7206     */
7207    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
7208        if (userId == UserHandle.USER_SYSTEM) {
7209            return resolveInfos;
7210        }
7211        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7212            ResolveInfo info = resolveInfos.get(i);
7213            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
7214                resolveInfos.remove(i);
7215            }
7216        }
7217        return resolveInfos;
7218    }
7219
7220    /**
7221     * Filters out ephemeral activities.
7222     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
7223     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
7224     *
7225     * @param resolveInfos The pre-filtered list of resolved activities
7226     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
7227     *          is performed.
7228     * @return A filtered list of resolved activities.
7229     */
7230    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
7231            String ephemeralPkgName) {
7232        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7233            final ResolveInfo info = resolveInfos.get(i);
7234            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
7235            // TODO: When adding on-demand split support for non-instant apps, remove this check
7236            // and always apply post filtering
7237            // allow activities that are defined in the provided package
7238            if (isEphemeralApp) {
7239                if (info.activityInfo.splitName != null
7240                        && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
7241                                info.activityInfo.splitName)) {
7242                    // requested activity is defined in a split that hasn't been installed yet.
7243                    // add the installer to the resolve list
7244                    if (DEBUG_EPHEMERAL) {
7245                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7246                    }
7247                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7248                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7249                            info.activityInfo.packageName, info.activityInfo.splitName,
7250                            info.activityInfo.applicationInfo.versionCode, null /*failureIntent*/);
7251                    // make sure this resolver is the default
7252                    installerInfo.isDefault = true;
7253                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7254                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7255                    // add a non-generic filter
7256                    installerInfo.filter = new IntentFilter();
7257                    // load resources from the correct package
7258                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7259                    resolveInfos.set(i, installerInfo);
7260                    continue;
7261                }
7262            }
7263            // caller is a full app, don't need to apply any other filtering
7264            if (ephemeralPkgName == null) {
7265                continue;
7266            } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
7267                // caller is same app; don't need to apply any other filtering
7268                continue;
7269            }
7270            // allow activities that have been explicitly exposed to ephemeral apps
7271            if (!isEphemeralApp
7272                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7273                continue;
7274            }
7275            resolveInfos.remove(i);
7276        }
7277        return resolveInfos;
7278    }
7279
7280    /**
7281     * @param resolveInfos list of resolve infos in descending priority order
7282     * @return if the list contains a resolve info with non-negative priority
7283     */
7284    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
7285        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
7286    }
7287
7288    private static boolean hasWebURI(Intent intent) {
7289        if (intent.getData() == null) {
7290            return false;
7291        }
7292        final String scheme = intent.getScheme();
7293        if (TextUtils.isEmpty(scheme)) {
7294            return false;
7295        }
7296        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
7297    }
7298
7299    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
7300            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
7301            int userId) {
7302        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
7303
7304        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7305            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
7306                    candidates.size());
7307        }
7308
7309        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
7310        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
7311        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
7312        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
7313        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
7314        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
7315
7316        synchronized (mPackages) {
7317            final int count = candidates.size();
7318            // First, try to use linked apps. Partition the candidates into four lists:
7319            // one for the final results, one for the "do not use ever", one for "undefined status"
7320            // and finally one for "browser app type".
7321            for (int n=0; n<count; n++) {
7322                ResolveInfo info = candidates.get(n);
7323                String packageName = info.activityInfo.packageName;
7324                PackageSetting ps = mSettings.mPackages.get(packageName);
7325                if (ps != null) {
7326                    // Add to the special match all list (Browser use case)
7327                    if (info.handleAllWebDataURI) {
7328                        matchAllList.add(info);
7329                        continue;
7330                    }
7331                    // Try to get the status from User settings first
7332                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7333                    int status = (int)(packedStatus >> 32);
7334                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7335                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
7336                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7337                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
7338                                    + " : linkgen=" + linkGeneration);
7339                        }
7340                        // Use link-enabled generation as preferredOrder, i.e.
7341                        // prefer newly-enabled over earlier-enabled.
7342                        info.preferredOrder = linkGeneration;
7343                        alwaysList.add(info);
7344                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7345                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7346                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
7347                        }
7348                        neverList.add(info);
7349                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
7350                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7351                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
7352                        }
7353                        alwaysAskList.add(info);
7354                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
7355                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
7356                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7357                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
7358                        }
7359                        undefinedList.add(info);
7360                    }
7361                }
7362            }
7363
7364            // We'll want to include browser possibilities in a few cases
7365            boolean includeBrowser = false;
7366
7367            // First try to add the "always" resolution(s) for the current user, if any
7368            if (alwaysList.size() > 0) {
7369                result.addAll(alwaysList);
7370            } else {
7371                // Add all undefined apps as we want them to appear in the disambiguation dialog.
7372                result.addAll(undefinedList);
7373                // Maybe add one for the other profile.
7374                if (xpDomainInfo != null && (
7375                        xpDomainInfo.bestDomainVerificationStatus
7376                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
7377                    result.add(xpDomainInfo.resolveInfo);
7378                }
7379                includeBrowser = true;
7380            }
7381
7382            // The presence of any 'always ask' alternatives means we'll also offer browsers.
7383            // If there were 'always' entries their preferred order has been set, so we also
7384            // back that off to make the alternatives equivalent
7385            if (alwaysAskList.size() > 0) {
7386                for (ResolveInfo i : result) {
7387                    i.preferredOrder = 0;
7388                }
7389                result.addAll(alwaysAskList);
7390                includeBrowser = true;
7391            }
7392
7393            if (includeBrowser) {
7394                // Also add browsers (all of them or only the default one)
7395                if (DEBUG_DOMAIN_VERIFICATION) {
7396                    Slog.v(TAG, "   ...including browsers in candidate set");
7397                }
7398                if ((matchFlags & MATCH_ALL) != 0) {
7399                    result.addAll(matchAllList);
7400                } else {
7401                    // Browser/generic handling case.  If there's a default browser, go straight
7402                    // to that (but only if there is no other higher-priority match).
7403                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7404                    int maxMatchPrio = 0;
7405                    ResolveInfo defaultBrowserMatch = null;
7406                    final int numCandidates = matchAllList.size();
7407                    for (int n = 0; n < numCandidates; n++) {
7408                        ResolveInfo info = matchAllList.get(n);
7409                        // track the highest overall match priority...
7410                        if (info.priority > maxMatchPrio) {
7411                            maxMatchPrio = info.priority;
7412                        }
7413                        // ...and the highest-priority default browser match
7414                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7415                            if (defaultBrowserMatch == null
7416                                    || (defaultBrowserMatch.priority < info.priority)) {
7417                                if (debug) {
7418                                    Slog.v(TAG, "Considering default browser match " + info);
7419                                }
7420                                defaultBrowserMatch = info;
7421                            }
7422                        }
7423                    }
7424                    if (defaultBrowserMatch != null
7425                            && defaultBrowserMatch.priority >= maxMatchPrio
7426                            && !TextUtils.isEmpty(defaultBrowserPackageName))
7427                    {
7428                        if (debug) {
7429                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7430                        }
7431                        result.add(defaultBrowserMatch);
7432                    } else {
7433                        result.addAll(matchAllList);
7434                    }
7435                }
7436
7437                // If there is nothing selected, add all candidates and remove the ones that the user
7438                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7439                if (result.size() == 0) {
7440                    result.addAll(candidates);
7441                    result.removeAll(neverList);
7442                }
7443            }
7444        }
7445        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7446            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7447                    result.size());
7448            for (ResolveInfo info : result) {
7449                Slog.v(TAG, "  + " + info.activityInfo);
7450            }
7451        }
7452        return result;
7453    }
7454
7455    // Returns a packed value as a long:
7456    //
7457    // high 'int'-sized word: link status: undefined/ask/never/always.
7458    // low 'int'-sized word: relative priority among 'always' results.
7459    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7460        long result = ps.getDomainVerificationStatusForUser(userId);
7461        // if none available, get the master status
7462        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7463            if (ps.getIntentFilterVerificationInfo() != null) {
7464                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7465            }
7466        }
7467        return result;
7468    }
7469
7470    private ResolveInfo querySkipCurrentProfileIntents(
7471            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7472            int flags, int sourceUserId) {
7473        if (matchingFilters != null) {
7474            int size = matchingFilters.size();
7475            for (int i = 0; i < size; i ++) {
7476                CrossProfileIntentFilter filter = matchingFilters.get(i);
7477                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7478                    // Checking if there are activities in the target user that can handle the
7479                    // intent.
7480                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7481                            resolvedType, flags, sourceUserId);
7482                    if (resolveInfo != null) {
7483                        return resolveInfo;
7484                    }
7485                }
7486            }
7487        }
7488        return null;
7489    }
7490
7491    // Return matching ResolveInfo in target user if any.
7492    private ResolveInfo queryCrossProfileIntents(
7493            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7494            int flags, int sourceUserId, boolean matchInCurrentProfile) {
7495        if (matchingFilters != null) {
7496            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7497            // match the same intent. For performance reasons, it is better not to
7498            // run queryIntent twice for the same userId
7499            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7500            int size = matchingFilters.size();
7501            for (int i = 0; i < size; i++) {
7502                CrossProfileIntentFilter filter = matchingFilters.get(i);
7503                int targetUserId = filter.getTargetUserId();
7504                boolean skipCurrentProfile =
7505                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7506                boolean skipCurrentProfileIfNoMatchFound =
7507                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7508                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7509                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7510                    // Checking if there are activities in the target user that can handle the
7511                    // intent.
7512                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7513                            resolvedType, flags, sourceUserId);
7514                    if (resolveInfo != null) return resolveInfo;
7515                    alreadyTriedUserIds.put(targetUserId, true);
7516                }
7517            }
7518        }
7519        return null;
7520    }
7521
7522    /**
7523     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7524     * will forward the intent to the filter's target user.
7525     * Otherwise, returns null.
7526     */
7527    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7528            String resolvedType, int flags, int sourceUserId) {
7529        int targetUserId = filter.getTargetUserId();
7530        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7531                resolvedType, flags, targetUserId);
7532        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7533            // If all the matches in the target profile are suspended, return null.
7534            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7535                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7536                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7537                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7538                            targetUserId);
7539                }
7540            }
7541        }
7542        return null;
7543    }
7544
7545    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7546            int sourceUserId, int targetUserId) {
7547        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7548        long ident = Binder.clearCallingIdentity();
7549        boolean targetIsProfile;
7550        try {
7551            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7552        } finally {
7553            Binder.restoreCallingIdentity(ident);
7554        }
7555        String className;
7556        if (targetIsProfile) {
7557            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7558        } else {
7559            className = FORWARD_INTENT_TO_PARENT;
7560        }
7561        ComponentName forwardingActivityComponentName = new ComponentName(
7562                mAndroidApplication.packageName, className);
7563        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7564                sourceUserId);
7565        if (!targetIsProfile) {
7566            forwardingActivityInfo.showUserIcon = targetUserId;
7567            forwardingResolveInfo.noResourceId = true;
7568        }
7569        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7570        forwardingResolveInfo.priority = 0;
7571        forwardingResolveInfo.preferredOrder = 0;
7572        forwardingResolveInfo.match = 0;
7573        forwardingResolveInfo.isDefault = true;
7574        forwardingResolveInfo.filter = filter;
7575        forwardingResolveInfo.targetUserId = targetUserId;
7576        return forwardingResolveInfo;
7577    }
7578
7579    @Override
7580    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7581            Intent[] specifics, String[] specificTypes, Intent intent,
7582            String resolvedType, int flags, int userId) {
7583        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7584                specificTypes, intent, resolvedType, flags, userId));
7585    }
7586
7587    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7588            Intent[] specifics, String[] specificTypes, Intent intent,
7589            String resolvedType, int flags, int userId) {
7590        if (!sUserManager.exists(userId)) return Collections.emptyList();
7591        final int callingUid = Binder.getCallingUid();
7592        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7593                false /*includeInstantApps*/);
7594        enforceCrossUserPermission(callingUid, userId,
7595                false /*requireFullPermission*/, false /*checkShell*/,
7596                "query intent activity options");
7597        final String resultsAction = intent.getAction();
7598
7599        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7600                | PackageManager.GET_RESOLVED_FILTER, userId);
7601
7602        if (DEBUG_INTENT_MATCHING) {
7603            Log.v(TAG, "Query " + intent + ": " + results);
7604        }
7605
7606        int specificsPos = 0;
7607        int N;
7608
7609        // todo: note that the algorithm used here is O(N^2).  This
7610        // isn't a problem in our current environment, but if we start running
7611        // into situations where we have more than 5 or 10 matches then this
7612        // should probably be changed to something smarter...
7613
7614        // First we go through and resolve each of the specific items
7615        // that were supplied, taking care of removing any corresponding
7616        // duplicate items in the generic resolve list.
7617        if (specifics != null) {
7618            for (int i=0; i<specifics.length; i++) {
7619                final Intent sintent = specifics[i];
7620                if (sintent == null) {
7621                    continue;
7622                }
7623
7624                if (DEBUG_INTENT_MATCHING) {
7625                    Log.v(TAG, "Specific #" + i + ": " + sintent);
7626                }
7627
7628                String action = sintent.getAction();
7629                if (resultsAction != null && resultsAction.equals(action)) {
7630                    // If this action was explicitly requested, then don't
7631                    // remove things that have it.
7632                    action = null;
7633                }
7634
7635                ResolveInfo ri = null;
7636                ActivityInfo ai = null;
7637
7638                ComponentName comp = sintent.getComponent();
7639                if (comp == null) {
7640                    ri = resolveIntent(
7641                        sintent,
7642                        specificTypes != null ? specificTypes[i] : null,
7643                            flags, userId);
7644                    if (ri == null) {
7645                        continue;
7646                    }
7647                    if (ri == mResolveInfo) {
7648                        // ACK!  Must do something better with this.
7649                    }
7650                    ai = ri.activityInfo;
7651                    comp = new ComponentName(ai.applicationInfo.packageName,
7652                            ai.name);
7653                } else {
7654                    ai = getActivityInfo(comp, flags, userId);
7655                    if (ai == null) {
7656                        continue;
7657                    }
7658                }
7659
7660                // Look for any generic query activities that are duplicates
7661                // of this specific one, and remove them from the results.
7662                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
7663                N = results.size();
7664                int j;
7665                for (j=specificsPos; j<N; j++) {
7666                    ResolveInfo sri = results.get(j);
7667                    if ((sri.activityInfo.name.equals(comp.getClassName())
7668                            && sri.activityInfo.applicationInfo.packageName.equals(
7669                                    comp.getPackageName()))
7670                        || (action != null && sri.filter.matchAction(action))) {
7671                        results.remove(j);
7672                        if (DEBUG_INTENT_MATCHING) Log.v(
7673                            TAG, "Removing duplicate item from " + j
7674                            + " due to specific " + specificsPos);
7675                        if (ri == null) {
7676                            ri = sri;
7677                        }
7678                        j--;
7679                        N--;
7680                    }
7681                }
7682
7683                // Add this specific item to its proper place.
7684                if (ri == null) {
7685                    ri = new ResolveInfo();
7686                    ri.activityInfo = ai;
7687                }
7688                results.add(specificsPos, ri);
7689                ri.specificIndex = i;
7690                specificsPos++;
7691            }
7692        }
7693
7694        // Now we go through the remaining generic results and remove any
7695        // duplicate actions that are found here.
7696        N = results.size();
7697        for (int i=specificsPos; i<N-1; i++) {
7698            final ResolveInfo rii = results.get(i);
7699            if (rii.filter == null) {
7700                continue;
7701            }
7702
7703            // Iterate over all of the actions of this result's intent
7704            // filter...  typically this should be just one.
7705            final Iterator<String> it = rii.filter.actionsIterator();
7706            if (it == null) {
7707                continue;
7708            }
7709            while (it.hasNext()) {
7710                final String action = it.next();
7711                if (resultsAction != null && resultsAction.equals(action)) {
7712                    // If this action was explicitly requested, then don't
7713                    // remove things that have it.
7714                    continue;
7715                }
7716                for (int j=i+1; j<N; j++) {
7717                    final ResolveInfo rij = results.get(j);
7718                    if (rij.filter != null && rij.filter.hasAction(action)) {
7719                        results.remove(j);
7720                        if (DEBUG_INTENT_MATCHING) Log.v(
7721                            TAG, "Removing duplicate item from " + j
7722                            + " due to action " + action + " at " + i);
7723                        j--;
7724                        N--;
7725                    }
7726                }
7727            }
7728
7729            // If the caller didn't request filter information, drop it now
7730            // so we don't have to marshall/unmarshall it.
7731            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7732                rii.filter = null;
7733            }
7734        }
7735
7736        // Filter out the caller activity if so requested.
7737        if (caller != null) {
7738            N = results.size();
7739            for (int i=0; i<N; i++) {
7740                ActivityInfo ainfo = results.get(i).activityInfo;
7741                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
7742                        && caller.getClassName().equals(ainfo.name)) {
7743                    results.remove(i);
7744                    break;
7745                }
7746            }
7747        }
7748
7749        // If the caller didn't request filter information,
7750        // drop them now so we don't have to
7751        // marshall/unmarshall it.
7752        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7753            N = results.size();
7754            for (int i=0; i<N; i++) {
7755                results.get(i).filter = null;
7756            }
7757        }
7758
7759        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
7760        return results;
7761    }
7762
7763    @Override
7764    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
7765            String resolvedType, int flags, int userId) {
7766        return new ParceledListSlice<>(
7767                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
7768    }
7769
7770    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
7771            String resolvedType, int flags, int userId) {
7772        if (!sUserManager.exists(userId)) return Collections.emptyList();
7773        final int callingUid = Binder.getCallingUid();
7774        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7775        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7776                false /*includeInstantApps*/);
7777        ComponentName comp = intent.getComponent();
7778        if (comp == null) {
7779            if (intent.getSelector() != null) {
7780                intent = intent.getSelector();
7781                comp = intent.getComponent();
7782            }
7783        }
7784        if (comp != null) {
7785            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7786            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
7787            if (ai != null) {
7788                // When specifying an explicit component, we prevent the activity from being
7789                // used when either 1) the calling package is normal and the activity is within
7790                // an instant application or 2) the calling package is ephemeral and the
7791                // activity is not visible to instant applications.
7792                final boolean matchInstantApp =
7793                        (flags & PackageManager.MATCH_INSTANT) != 0;
7794                final boolean matchVisibleToInstantAppOnly =
7795                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7796                final boolean matchExplicitlyVisibleOnly =
7797                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7798                final boolean isCallerInstantApp =
7799                        instantAppPkgName != null;
7800                final boolean isTargetSameInstantApp =
7801                        comp.getPackageName().equals(instantAppPkgName);
7802                final boolean isTargetInstantApp =
7803                        (ai.applicationInfo.privateFlags
7804                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7805                final boolean isTargetVisibleToInstantApp =
7806                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7807                final boolean isTargetExplicitlyVisibleToInstantApp =
7808                        isTargetVisibleToInstantApp
7809                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7810                final boolean isTargetHiddenFromInstantApp =
7811                        !isTargetVisibleToInstantApp
7812                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7813                final boolean blockResolution =
7814                        !isTargetSameInstantApp
7815                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7816                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7817                                        && isTargetHiddenFromInstantApp));
7818                if (!blockResolution) {
7819                    ResolveInfo ri = new ResolveInfo();
7820                    ri.activityInfo = ai;
7821                    list.add(ri);
7822                }
7823            }
7824            return applyPostResolutionFilter(list, instantAppPkgName);
7825        }
7826
7827        // reader
7828        synchronized (mPackages) {
7829            String pkgName = intent.getPackage();
7830            if (pkgName == null) {
7831                final List<ResolveInfo> result =
7832                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
7833                return applyPostResolutionFilter(result, instantAppPkgName);
7834            }
7835            final PackageParser.Package pkg = mPackages.get(pkgName);
7836            if (pkg != null) {
7837                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
7838                        intent, resolvedType, flags, pkg.receivers, userId);
7839                return applyPostResolutionFilter(result, instantAppPkgName);
7840            }
7841            return Collections.emptyList();
7842        }
7843    }
7844
7845    @Override
7846    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7847        final int callingUid = Binder.getCallingUid();
7848        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
7849    }
7850
7851    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
7852            int userId, int callingUid) {
7853        if (!sUserManager.exists(userId)) return null;
7854        flags = updateFlagsForResolve(
7855                flags, userId, intent, callingUid, false /*includeInstantApps*/);
7856        List<ResolveInfo> query = queryIntentServicesInternal(
7857                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
7858        if (query != null) {
7859            if (query.size() >= 1) {
7860                // If there is more than one service with the same priority,
7861                // just arbitrarily pick the first one.
7862                return query.get(0);
7863            }
7864        }
7865        return null;
7866    }
7867
7868    @Override
7869    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7870            String resolvedType, int flags, int userId) {
7871        final int callingUid = Binder.getCallingUid();
7872        return new ParceledListSlice<>(queryIntentServicesInternal(
7873                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
7874    }
7875
7876    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7877            String resolvedType, int flags, int userId, int callingUid,
7878            boolean includeInstantApps) {
7879        if (!sUserManager.exists(userId)) return Collections.emptyList();
7880        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7881        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7882        ComponentName comp = intent.getComponent();
7883        if (comp == null) {
7884            if (intent.getSelector() != null) {
7885                intent = intent.getSelector();
7886                comp = intent.getComponent();
7887            }
7888        }
7889        if (comp != null) {
7890            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7891            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7892            if (si != null) {
7893                // When specifying an explicit component, we prevent the service from being
7894                // used when either 1) the service is in an instant application and the
7895                // caller is not the same instant application or 2) the calling package is
7896                // ephemeral and the activity is not visible to ephemeral applications.
7897                final boolean matchInstantApp =
7898                        (flags & PackageManager.MATCH_INSTANT) != 0;
7899                final boolean matchVisibleToInstantAppOnly =
7900                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7901                final boolean isCallerInstantApp =
7902                        instantAppPkgName != null;
7903                final boolean isTargetSameInstantApp =
7904                        comp.getPackageName().equals(instantAppPkgName);
7905                final boolean isTargetInstantApp =
7906                        (si.applicationInfo.privateFlags
7907                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7908                final boolean isTargetHiddenFromInstantApp =
7909                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7910                final boolean blockResolution =
7911                        !isTargetSameInstantApp
7912                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7913                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7914                                        && isTargetHiddenFromInstantApp));
7915                if (!blockResolution) {
7916                    final ResolveInfo ri = new ResolveInfo();
7917                    ri.serviceInfo = si;
7918                    list.add(ri);
7919                }
7920            }
7921            return list;
7922        }
7923
7924        // reader
7925        synchronized (mPackages) {
7926            String pkgName = intent.getPackage();
7927            if (pkgName == null) {
7928                return applyPostServiceResolutionFilter(
7929                        mServices.queryIntent(intent, resolvedType, flags, userId),
7930                        instantAppPkgName);
7931            }
7932            final PackageParser.Package pkg = mPackages.get(pkgName);
7933            if (pkg != null) {
7934                return applyPostServiceResolutionFilter(
7935                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7936                                userId),
7937                        instantAppPkgName);
7938            }
7939            return Collections.emptyList();
7940        }
7941    }
7942
7943    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
7944            String instantAppPkgName) {
7945        // TODO: When adding on-demand split support for non-instant apps, remove this check
7946        // and always apply post filtering
7947        if (instantAppPkgName == null) {
7948            return resolveInfos;
7949        }
7950        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7951            final ResolveInfo info = resolveInfos.get(i);
7952            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
7953            // allow services that are defined in the provided package
7954            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
7955                if (info.serviceInfo.splitName != null
7956                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
7957                                info.serviceInfo.splitName)) {
7958                    // requested service is defined in a split that hasn't been installed yet.
7959                    // add the installer to the resolve list
7960                    if (DEBUG_EPHEMERAL) {
7961                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7962                    }
7963                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7964                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7965                            info.serviceInfo.packageName, info.serviceInfo.splitName,
7966                            info.serviceInfo.applicationInfo.versionCode, null /*failureIntent*/);
7967                    // make sure this resolver is the default
7968                    installerInfo.isDefault = true;
7969                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7970                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7971                    // add a non-generic filter
7972                    installerInfo.filter = new IntentFilter();
7973                    // load resources from the correct package
7974                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7975                    resolveInfos.set(i, installerInfo);
7976                }
7977                continue;
7978            }
7979            // allow services that have been explicitly exposed to ephemeral apps
7980            if (!isEphemeralApp
7981                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7982                continue;
7983            }
7984            resolveInfos.remove(i);
7985        }
7986        return resolveInfos;
7987    }
7988
7989    @Override
7990    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7991            String resolvedType, int flags, int userId) {
7992        return new ParceledListSlice<>(
7993                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7994    }
7995
7996    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7997            Intent intent, String resolvedType, int flags, int userId) {
7998        if (!sUserManager.exists(userId)) return Collections.emptyList();
7999        final int callingUid = Binder.getCallingUid();
8000        final String instantAppPkgName = getInstantAppPackageName(callingUid);
8001        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
8002                false /*includeInstantApps*/);
8003        ComponentName comp = intent.getComponent();
8004        if (comp == null) {
8005            if (intent.getSelector() != null) {
8006                intent = intent.getSelector();
8007                comp = intent.getComponent();
8008            }
8009        }
8010        if (comp != null) {
8011            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
8012            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
8013            if (pi != null) {
8014                // When specifying an explicit component, we prevent the provider from being
8015                // used when either 1) the provider is in an instant application and the
8016                // caller is not the same instant application or 2) the calling package is an
8017                // instant application and the provider is not visible to instant applications.
8018                final boolean matchInstantApp =
8019                        (flags & PackageManager.MATCH_INSTANT) != 0;
8020                final boolean matchVisibleToInstantAppOnly =
8021                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8022                final boolean isCallerInstantApp =
8023                        instantAppPkgName != null;
8024                final boolean isTargetSameInstantApp =
8025                        comp.getPackageName().equals(instantAppPkgName);
8026                final boolean isTargetInstantApp =
8027                        (pi.applicationInfo.privateFlags
8028                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8029                final boolean isTargetHiddenFromInstantApp =
8030                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
8031                final boolean blockResolution =
8032                        !isTargetSameInstantApp
8033                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8034                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
8035                                        && isTargetHiddenFromInstantApp));
8036                if (!blockResolution) {
8037                    final ResolveInfo ri = new ResolveInfo();
8038                    ri.providerInfo = pi;
8039                    list.add(ri);
8040                }
8041            }
8042            return list;
8043        }
8044
8045        // reader
8046        synchronized (mPackages) {
8047            String pkgName = intent.getPackage();
8048            if (pkgName == null) {
8049                return applyPostContentProviderResolutionFilter(
8050                        mProviders.queryIntent(intent, resolvedType, flags, userId),
8051                        instantAppPkgName);
8052            }
8053            final PackageParser.Package pkg = mPackages.get(pkgName);
8054            if (pkg != null) {
8055                return applyPostContentProviderResolutionFilter(
8056                        mProviders.queryIntentForPackage(
8057                        intent, resolvedType, flags, pkg.providers, userId),
8058                        instantAppPkgName);
8059            }
8060            return Collections.emptyList();
8061        }
8062    }
8063
8064    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
8065            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
8066        // TODO: When adding on-demand split support for non-instant applications, remove
8067        // this check and always apply post filtering
8068        if (instantAppPkgName == null) {
8069            return resolveInfos;
8070        }
8071        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
8072            final ResolveInfo info = resolveInfos.get(i);
8073            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
8074            // allow providers that are defined in the provided package
8075            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
8076                if (info.providerInfo.splitName != null
8077                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
8078                                info.providerInfo.splitName)) {
8079                    // requested provider is defined in a split that hasn't been installed yet.
8080                    // add the installer to the resolve list
8081                    if (DEBUG_EPHEMERAL) {
8082                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
8083                    }
8084                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
8085                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
8086                            info.providerInfo.packageName, info.providerInfo.splitName,
8087                            info.providerInfo.applicationInfo.versionCode, null /*failureIntent*/);
8088                    // make sure this resolver is the default
8089                    installerInfo.isDefault = true;
8090                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
8091                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
8092                    // add a non-generic filter
8093                    installerInfo.filter = new IntentFilter();
8094                    // load resources from the correct package
8095                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
8096                    resolveInfos.set(i, installerInfo);
8097                }
8098                continue;
8099            }
8100            // allow providers that have been explicitly exposed to instant applications
8101            if (!isEphemeralApp
8102                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
8103                continue;
8104            }
8105            resolveInfos.remove(i);
8106        }
8107        return resolveInfos;
8108    }
8109
8110    @Override
8111    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
8112        final int callingUid = Binder.getCallingUid();
8113        if (getInstantAppPackageName(callingUid) != null) {
8114            return ParceledListSlice.emptyList();
8115        }
8116        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8117        flags = updateFlagsForPackage(flags, userId, null);
8118        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8119        enforceCrossUserPermission(callingUid, userId,
8120                true /* requireFullPermission */, false /* checkShell */,
8121                "get installed packages");
8122
8123        // writer
8124        synchronized (mPackages) {
8125            ArrayList<PackageInfo> list;
8126            if (listUninstalled) {
8127                list = new ArrayList<>(mSettings.mPackages.size());
8128                for (PackageSetting ps : mSettings.mPackages.values()) {
8129                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8130                        continue;
8131                    }
8132                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8133                        return null;
8134                    }
8135                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8136                    if (pi != null) {
8137                        list.add(pi);
8138                    }
8139                }
8140            } else {
8141                list = new ArrayList<>(mPackages.size());
8142                for (PackageParser.Package p : mPackages.values()) {
8143                    final PackageSetting ps = (PackageSetting) p.mExtras;
8144                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8145                        continue;
8146                    }
8147                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8148                        return null;
8149                    }
8150                    final PackageInfo pi = generatePackageInfo((PackageSetting)
8151                            p.mExtras, flags, userId);
8152                    if (pi != null) {
8153                        list.add(pi);
8154                    }
8155                }
8156            }
8157
8158            return new ParceledListSlice<>(list);
8159        }
8160    }
8161
8162    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
8163            String[] permissions, boolean[] tmp, int flags, int userId) {
8164        int numMatch = 0;
8165        final PermissionsState permissionsState = ps.getPermissionsState();
8166        for (int i=0; i<permissions.length; i++) {
8167            final String permission = permissions[i];
8168            if (permissionsState.hasPermission(permission, userId)) {
8169                tmp[i] = true;
8170                numMatch++;
8171            } else {
8172                tmp[i] = false;
8173            }
8174        }
8175        if (numMatch == 0) {
8176            return;
8177        }
8178        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8179
8180        // The above might return null in cases of uninstalled apps or install-state
8181        // skew across users/profiles.
8182        if (pi != null) {
8183            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
8184                if (numMatch == permissions.length) {
8185                    pi.requestedPermissions = permissions;
8186                } else {
8187                    pi.requestedPermissions = new String[numMatch];
8188                    numMatch = 0;
8189                    for (int i=0; i<permissions.length; i++) {
8190                        if (tmp[i]) {
8191                            pi.requestedPermissions[numMatch] = permissions[i];
8192                            numMatch++;
8193                        }
8194                    }
8195                }
8196            }
8197            list.add(pi);
8198        }
8199    }
8200
8201    @Override
8202    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
8203            String[] permissions, int flags, int userId) {
8204        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8205        flags = updateFlagsForPackage(flags, userId, permissions);
8206        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8207                true /* requireFullPermission */, false /* checkShell */,
8208                "get packages holding permissions");
8209        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8210
8211        // writer
8212        synchronized (mPackages) {
8213            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
8214            boolean[] tmpBools = new boolean[permissions.length];
8215            if (listUninstalled) {
8216                for (PackageSetting ps : mSettings.mPackages.values()) {
8217                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8218                            userId);
8219                }
8220            } else {
8221                for (PackageParser.Package pkg : mPackages.values()) {
8222                    PackageSetting ps = (PackageSetting)pkg.mExtras;
8223                    if (ps != null) {
8224                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8225                                userId);
8226                    }
8227                }
8228            }
8229
8230            return new ParceledListSlice<PackageInfo>(list);
8231        }
8232    }
8233
8234    @Override
8235    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
8236        final int callingUid = Binder.getCallingUid();
8237        if (getInstantAppPackageName(callingUid) != null) {
8238            return ParceledListSlice.emptyList();
8239        }
8240        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8241        flags = updateFlagsForApplication(flags, userId, null);
8242        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8243
8244        // writer
8245        synchronized (mPackages) {
8246            ArrayList<ApplicationInfo> list;
8247            if (listUninstalled) {
8248                list = new ArrayList<>(mSettings.mPackages.size());
8249                for (PackageSetting ps : mSettings.mPackages.values()) {
8250                    ApplicationInfo ai;
8251                    int effectiveFlags = flags;
8252                    if (ps.isSystem()) {
8253                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
8254                    }
8255                    if (ps.pkg != null) {
8256                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8257                            continue;
8258                        }
8259                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8260                            return null;
8261                        }
8262                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
8263                                ps.readUserState(userId), userId);
8264                        if (ai != null) {
8265                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
8266                        }
8267                    } else {
8268                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
8269                        // and already converts to externally visible package name
8270                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
8271                                callingUid, effectiveFlags, userId);
8272                    }
8273                    if (ai != null) {
8274                        list.add(ai);
8275                    }
8276                }
8277            } else {
8278                list = new ArrayList<>(mPackages.size());
8279                for (PackageParser.Package p : mPackages.values()) {
8280                    if (p.mExtras != null) {
8281                        PackageSetting ps = (PackageSetting) p.mExtras;
8282                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
8283                            continue;
8284                        }
8285                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8286                            return null;
8287                        }
8288                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8289                                ps.readUserState(userId), userId);
8290                        if (ai != null) {
8291                            ai.packageName = resolveExternalPackageNameLPr(p);
8292                            list.add(ai);
8293                        }
8294                    }
8295                }
8296            }
8297
8298            return new ParceledListSlice<>(list);
8299        }
8300    }
8301
8302    @Override
8303    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
8304        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8305            return null;
8306        }
8307        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8308                "getEphemeralApplications");
8309        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8310                true /* requireFullPermission */, false /* checkShell */,
8311                "getEphemeralApplications");
8312        synchronized (mPackages) {
8313            List<InstantAppInfo> instantApps = mInstantAppRegistry
8314                    .getInstantAppsLPr(userId);
8315            if (instantApps != null) {
8316                return new ParceledListSlice<>(instantApps);
8317            }
8318        }
8319        return null;
8320    }
8321
8322    @Override
8323    public boolean isInstantApp(String packageName, int userId) {
8324        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8325                true /* requireFullPermission */, false /* checkShell */,
8326                "isInstantApp");
8327        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8328            return false;
8329        }
8330        int callingUid = Binder.getCallingUid();
8331        if (Process.isIsolated(callingUid)) {
8332            callingUid = mIsolatedOwners.get(callingUid);
8333        }
8334
8335        synchronized (mPackages) {
8336            final PackageSetting ps = mSettings.mPackages.get(packageName);
8337            PackageParser.Package pkg = mPackages.get(packageName);
8338            final boolean returnAllowed =
8339                    ps != null
8340                    && (isCallerSameApp(packageName, callingUid)
8341                            || canViewInstantApps(callingUid, userId)
8342                            || mInstantAppRegistry.isInstantAccessGranted(
8343                                    userId, UserHandle.getAppId(callingUid), ps.appId));
8344            if (returnAllowed) {
8345                return ps.getInstantApp(userId);
8346            }
8347        }
8348        return false;
8349    }
8350
8351    @Override
8352    public byte[] getInstantAppCookie(String packageName, int userId) {
8353        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8354            return null;
8355        }
8356
8357        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8358                true /* requireFullPermission */, false /* checkShell */,
8359                "getInstantAppCookie");
8360        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8361            return null;
8362        }
8363        synchronized (mPackages) {
8364            return mInstantAppRegistry.getInstantAppCookieLPw(
8365                    packageName, userId);
8366        }
8367    }
8368
8369    @Override
8370    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8371        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8372            return true;
8373        }
8374
8375        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8376                true /* requireFullPermission */, true /* checkShell */,
8377                "setInstantAppCookie");
8378        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8379            return false;
8380        }
8381        synchronized (mPackages) {
8382            return mInstantAppRegistry.setInstantAppCookieLPw(
8383                    packageName, cookie, userId);
8384        }
8385    }
8386
8387    @Override
8388    public Bitmap getInstantAppIcon(String packageName, int userId) {
8389        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8390            return null;
8391        }
8392
8393        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8394                "getInstantAppIcon");
8395
8396        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8397                true /* requireFullPermission */, false /* checkShell */,
8398                "getInstantAppIcon");
8399
8400        synchronized (mPackages) {
8401            return mInstantAppRegistry.getInstantAppIconLPw(
8402                    packageName, userId);
8403        }
8404    }
8405
8406    private boolean isCallerSameApp(String packageName, int uid) {
8407        PackageParser.Package pkg = mPackages.get(packageName);
8408        return pkg != null
8409                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8410    }
8411
8412    @Override
8413    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8414        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8415            return ParceledListSlice.emptyList();
8416        }
8417        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8418    }
8419
8420    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8421        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8422
8423        // reader
8424        synchronized (mPackages) {
8425            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8426            final int userId = UserHandle.getCallingUserId();
8427            while (i.hasNext()) {
8428                final PackageParser.Package p = i.next();
8429                if (p.applicationInfo == null) continue;
8430
8431                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8432                        && !p.applicationInfo.isDirectBootAware();
8433                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8434                        && p.applicationInfo.isDirectBootAware();
8435
8436                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8437                        && (!mSafeMode || isSystemApp(p))
8438                        && (matchesUnaware || matchesAware)) {
8439                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
8440                    if (ps != null) {
8441                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8442                                ps.readUserState(userId), userId);
8443                        if (ai != null) {
8444                            finalList.add(ai);
8445                        }
8446                    }
8447                }
8448            }
8449        }
8450
8451        return finalList;
8452    }
8453
8454    @Override
8455    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8456        if (!sUserManager.exists(userId)) return null;
8457        flags = updateFlagsForComponent(flags, userId, name);
8458        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
8459        // reader
8460        synchronized (mPackages) {
8461            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8462            PackageSetting ps = provider != null
8463                    ? mSettings.mPackages.get(provider.owner.packageName)
8464                    : null;
8465            if (ps != null) {
8466                final boolean isInstantApp = ps.getInstantApp(userId);
8467                // normal application; filter out instant application provider
8468                if (instantAppPkgName == null && isInstantApp) {
8469                    return null;
8470                }
8471                // instant application; filter out other instant applications
8472                if (instantAppPkgName != null
8473                        && isInstantApp
8474                        && !provider.owner.packageName.equals(instantAppPkgName)) {
8475                    return null;
8476                }
8477                // instant application; filter out non-exposed provider
8478                if (instantAppPkgName != null
8479                        && !isInstantApp
8480                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
8481                    return null;
8482                }
8483                // provider not enabled
8484                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8485                    return null;
8486                }
8487                return PackageParser.generateProviderInfo(
8488                        provider, flags, ps.readUserState(userId), userId);
8489            }
8490            return null;
8491        }
8492    }
8493
8494    /**
8495     * @deprecated
8496     */
8497    @Deprecated
8498    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8499        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8500            return;
8501        }
8502        // reader
8503        synchronized (mPackages) {
8504            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8505                    .entrySet().iterator();
8506            final int userId = UserHandle.getCallingUserId();
8507            while (i.hasNext()) {
8508                Map.Entry<String, PackageParser.Provider> entry = i.next();
8509                PackageParser.Provider p = entry.getValue();
8510                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8511
8512                if (ps != null && p.syncable
8513                        && (!mSafeMode || (p.info.applicationInfo.flags
8514                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8515                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8516                            ps.readUserState(userId), userId);
8517                    if (info != null) {
8518                        outNames.add(entry.getKey());
8519                        outInfo.add(info);
8520                    }
8521                }
8522            }
8523        }
8524    }
8525
8526    @Override
8527    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8528            int uid, int flags, String metaDataKey) {
8529        final int callingUid = Binder.getCallingUid();
8530        final int userId = processName != null ? UserHandle.getUserId(uid)
8531                : UserHandle.getCallingUserId();
8532        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8533        flags = updateFlagsForComponent(flags, userId, processName);
8534        ArrayList<ProviderInfo> finalList = null;
8535        // reader
8536        synchronized (mPackages) {
8537            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8538            while (i.hasNext()) {
8539                final PackageParser.Provider p = i.next();
8540                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8541                if (ps != null && p.info.authority != null
8542                        && (processName == null
8543                                || (p.info.processName.equals(processName)
8544                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8545                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8546
8547                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8548                    // parameter.
8549                    if (metaDataKey != null
8550                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8551                        continue;
8552                    }
8553                    final ComponentName component =
8554                            new ComponentName(p.info.packageName, p.info.name);
8555                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8556                        continue;
8557                    }
8558                    if (finalList == null) {
8559                        finalList = new ArrayList<ProviderInfo>(3);
8560                    }
8561                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8562                            ps.readUserState(userId), userId);
8563                    if (info != null) {
8564                        finalList.add(info);
8565                    }
8566                }
8567            }
8568        }
8569
8570        if (finalList != null) {
8571            Collections.sort(finalList, mProviderInitOrderSorter);
8572            return new ParceledListSlice<ProviderInfo>(finalList);
8573        }
8574
8575        return ParceledListSlice.emptyList();
8576    }
8577
8578    @Override
8579    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8580        // reader
8581        synchronized (mPackages) {
8582            final int callingUid = Binder.getCallingUid();
8583            final int callingUserId = UserHandle.getUserId(callingUid);
8584            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8585            if (ps == null) return null;
8586            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8587                return null;
8588            }
8589            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8590            return PackageParser.generateInstrumentationInfo(i, flags);
8591        }
8592    }
8593
8594    @Override
8595    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8596            String targetPackage, int flags) {
8597        final int callingUid = Binder.getCallingUid();
8598        final int callingUserId = UserHandle.getUserId(callingUid);
8599        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8600        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8601            return ParceledListSlice.emptyList();
8602        }
8603        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8604    }
8605
8606    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8607            int flags) {
8608        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8609
8610        // reader
8611        synchronized (mPackages) {
8612            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8613            while (i.hasNext()) {
8614                final PackageParser.Instrumentation p = i.next();
8615                if (targetPackage == null
8616                        || targetPackage.equals(p.info.targetPackage)) {
8617                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8618                            flags);
8619                    if (ii != null) {
8620                        finalList.add(ii);
8621                    }
8622                }
8623            }
8624        }
8625
8626        return finalList;
8627    }
8628
8629    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
8630        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
8631        try {
8632            scanDirLI(dir, parseFlags, scanFlags, currentTime);
8633        } finally {
8634            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8635        }
8636    }
8637
8638    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
8639        final File[] files = dir.listFiles();
8640        if (ArrayUtils.isEmpty(files)) {
8641            Log.d(TAG, "No files in app dir " + dir);
8642            return;
8643        }
8644
8645        if (DEBUG_PACKAGE_SCANNING) {
8646            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
8647                    + " flags=0x" + Integer.toHexString(parseFlags));
8648        }
8649        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
8650                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
8651                mParallelPackageParserCallback);
8652
8653        // Submit files for parsing in parallel
8654        int fileCount = 0;
8655        for (File file : files) {
8656            final boolean isPackage = (isApkFile(file) || file.isDirectory())
8657                    && !PackageInstallerService.isStageName(file.getName());
8658            if (!isPackage) {
8659                // Ignore entries which are not packages
8660                continue;
8661            }
8662            parallelPackageParser.submit(file, parseFlags);
8663            fileCount++;
8664        }
8665
8666        // Process results one by one
8667        for (; fileCount > 0; fileCount--) {
8668            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
8669            Throwable throwable = parseResult.throwable;
8670            int errorCode = PackageManager.INSTALL_SUCCEEDED;
8671
8672            if (throwable == null) {
8673                // Static shared libraries have synthetic package names
8674                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
8675                    renameStaticSharedLibraryPackage(parseResult.pkg);
8676                }
8677                try {
8678                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
8679                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
8680                                currentTime, null);
8681                    }
8682                } catch (PackageManagerException e) {
8683                    errorCode = e.error;
8684                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
8685                }
8686            } else if (throwable instanceof PackageParser.PackageParserException) {
8687                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
8688                        throwable;
8689                errorCode = e.error;
8690                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
8691            } else {
8692                throw new IllegalStateException("Unexpected exception occurred while parsing "
8693                        + parseResult.scanFile, throwable);
8694            }
8695
8696            // Delete invalid userdata apps
8697            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
8698                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
8699                logCriticalInfo(Log.WARN,
8700                        "Deleting invalid package at " + parseResult.scanFile);
8701                removeCodePathLI(parseResult.scanFile);
8702            }
8703        }
8704        parallelPackageParser.close();
8705    }
8706
8707    private static File getSettingsProblemFile() {
8708        File dataDir = Environment.getDataDirectory();
8709        File systemDir = new File(dataDir, "system");
8710        File fname = new File(systemDir, "uiderrors.txt");
8711        return fname;
8712    }
8713
8714    static void reportSettingsProblem(int priority, String msg) {
8715        logCriticalInfo(priority, msg);
8716    }
8717
8718    public static void logCriticalInfo(int priority, String msg) {
8719        Slog.println(priority, TAG, msg);
8720        EventLogTags.writePmCriticalInfo(msg);
8721        try {
8722            File fname = getSettingsProblemFile();
8723            FileOutputStream out = new FileOutputStream(fname, true);
8724            PrintWriter pw = new FastPrintWriter(out);
8725            SimpleDateFormat formatter = new SimpleDateFormat();
8726            String dateString = formatter.format(new Date(System.currentTimeMillis()));
8727            pw.println(dateString + ": " + msg);
8728            pw.close();
8729            FileUtils.setPermissions(
8730                    fname.toString(),
8731                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
8732                    -1, -1);
8733        } catch (java.io.IOException e) {
8734        }
8735    }
8736
8737    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
8738        if (srcFile.isDirectory()) {
8739            final File baseFile = new File(pkg.baseCodePath);
8740            long maxModifiedTime = baseFile.lastModified();
8741            if (pkg.splitCodePaths != null) {
8742                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
8743                    final File splitFile = new File(pkg.splitCodePaths[i]);
8744                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
8745                }
8746            }
8747            return maxModifiedTime;
8748        }
8749        return srcFile.lastModified();
8750    }
8751
8752    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
8753            final int policyFlags) throws PackageManagerException {
8754        // When upgrading from pre-N MR1, verify the package time stamp using the package
8755        // directory and not the APK file.
8756        final long lastModifiedTime = mIsPreNMR1Upgrade
8757                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
8758        if (ps != null
8759                && ps.codePath.equals(srcFile)
8760                && ps.timeStamp == lastModifiedTime
8761                && !isCompatSignatureUpdateNeeded(pkg)
8762                && !isRecoverSignatureUpdateNeeded(pkg)) {
8763            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
8764            KeySetManagerService ksms = mSettings.mKeySetManagerService;
8765            ArraySet<PublicKey> signingKs;
8766            synchronized (mPackages) {
8767                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
8768            }
8769            if (ps.signatures.mSignatures != null
8770                    && ps.signatures.mSignatures.length != 0
8771                    && signingKs != null) {
8772                // Optimization: reuse the existing cached certificates
8773                // if the package appears to be unchanged.
8774                pkg.mSignatures = ps.signatures.mSignatures;
8775                pkg.mSigningKeys = signingKs;
8776                return;
8777            }
8778
8779            Slog.w(TAG, "PackageSetting for " + ps.name
8780                    + " is missing signatures.  Collecting certs again to recover them.");
8781        } else {
8782            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
8783        }
8784
8785        try {
8786            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
8787            PackageParser.collectCertificates(pkg, policyFlags);
8788        } catch (PackageParserException e) {
8789            throw PackageManagerException.from(e);
8790        } finally {
8791            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8792        }
8793    }
8794
8795    /**
8796     *  Traces a package scan.
8797     *  @see #scanPackageLI(File, int, int, long, UserHandle)
8798     */
8799    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
8800            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8801        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
8802        try {
8803            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
8804        } finally {
8805            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8806        }
8807    }
8808
8809    /**
8810     *  Scans a package and returns the newly parsed package.
8811     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
8812     */
8813    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
8814            long currentTime, UserHandle user) throws PackageManagerException {
8815        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
8816        PackageParser pp = new PackageParser();
8817        pp.setSeparateProcesses(mSeparateProcesses);
8818        pp.setOnlyCoreApps(mOnlyCore);
8819        pp.setDisplayMetrics(mMetrics);
8820        pp.setCallback(mPackageParserCallback);
8821
8822        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
8823            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
8824        }
8825
8826        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
8827        final PackageParser.Package pkg;
8828        try {
8829            pkg = pp.parsePackage(scanFile, parseFlags);
8830        } catch (PackageParserException e) {
8831            throw PackageManagerException.from(e);
8832        } finally {
8833            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8834        }
8835
8836        // Static shared libraries have synthetic package names
8837        if (pkg.applicationInfo.isStaticSharedLibrary()) {
8838            renameStaticSharedLibraryPackage(pkg);
8839        }
8840
8841        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
8842    }
8843
8844    /**
8845     *  Scans a package and returns the newly parsed package.
8846     *  @throws PackageManagerException on a parse error.
8847     */
8848    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
8849            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8850            throws PackageManagerException {
8851        // If the package has children and this is the first dive in the function
8852        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
8853        // packages (parent and children) would be successfully scanned before the
8854        // actual scan since scanning mutates internal state and we want to atomically
8855        // install the package and its children.
8856        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8857            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8858                scanFlags |= SCAN_CHECK_ONLY;
8859            }
8860        } else {
8861            scanFlags &= ~SCAN_CHECK_ONLY;
8862        }
8863
8864        // Scan the parent
8865        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
8866                scanFlags, currentTime, user);
8867
8868        // Scan the children
8869        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8870        for (int i = 0; i < childCount; i++) {
8871            PackageParser.Package childPackage = pkg.childPackages.get(i);
8872            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
8873                    currentTime, user);
8874        }
8875
8876
8877        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8878            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
8879        }
8880
8881        return scannedPkg;
8882    }
8883
8884    /**
8885     *  Scans a package and returns the newly parsed package.
8886     *  @throws PackageManagerException on a parse error.
8887     */
8888    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
8889            int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8890            throws PackageManagerException {
8891        PackageSetting ps = null;
8892        PackageSetting updatedPkg;
8893        // reader
8894        synchronized (mPackages) {
8895            // Look to see if we already know about this package.
8896            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
8897            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
8898                // This package has been renamed to its original name.  Let's
8899                // use that.
8900                ps = mSettings.getPackageLPr(oldName);
8901            }
8902            // If there was no original package, see one for the real package name.
8903            if (ps == null) {
8904                ps = mSettings.getPackageLPr(pkg.packageName);
8905            }
8906            // Check to see if this package could be hiding/updating a system
8907            // package.  Must look for it either under the original or real
8908            // package name depending on our state.
8909            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
8910            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
8911
8912            // If this is a package we don't know about on the system partition, we
8913            // may need to remove disabled child packages on the system partition
8914            // or may need to not add child packages if the parent apk is updated
8915            // on the data partition and no longer defines this child package.
8916            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
8917                // If this is a parent package for an updated system app and this system
8918                // app got an OTA update which no longer defines some of the child packages
8919                // we have to prune them from the disabled system packages.
8920                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8921                if (disabledPs != null) {
8922                    final int scannedChildCount = (pkg.childPackages != null)
8923                            ? pkg.childPackages.size() : 0;
8924                    final int disabledChildCount = disabledPs.childPackageNames != null
8925                            ? disabledPs.childPackageNames.size() : 0;
8926                    for (int i = 0; i < disabledChildCount; i++) {
8927                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
8928                        boolean disabledPackageAvailable = false;
8929                        for (int j = 0; j < scannedChildCount; j++) {
8930                            PackageParser.Package childPkg = pkg.childPackages.get(j);
8931                            if (childPkg.packageName.equals(disabledChildPackageName)) {
8932                                disabledPackageAvailable = true;
8933                                break;
8934                            }
8935                         }
8936                         if (!disabledPackageAvailable) {
8937                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
8938                         }
8939                    }
8940                }
8941            }
8942        }
8943
8944        final boolean isUpdatedPkg = updatedPkg != null;
8945        final boolean isUpdatedSystemPkg = isUpdatedPkg
8946                && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0;
8947        boolean isUpdatedPkgBetter = false;
8948        // First check if this is a system package that may involve an update
8949        if (isUpdatedSystemPkg) {
8950            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
8951            // it needs to drop FLAG_PRIVILEGED.
8952            if (locationIsPrivileged(scanFile)) {
8953                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8954            } else {
8955                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8956            }
8957
8958            if (ps != null && !ps.codePath.equals(scanFile)) {
8959                // The path has changed from what was last scanned...  check the
8960                // version of the new path against what we have stored to determine
8961                // what to do.
8962                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
8963                if (pkg.mVersionCode <= ps.versionCode) {
8964                    // The system package has been updated and the code path does not match
8965                    // Ignore entry. Skip it.
8966                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
8967                            + " ignored: updated version " + ps.versionCode
8968                            + " better than this " + pkg.mVersionCode);
8969                    if (!updatedPkg.codePath.equals(scanFile)) {
8970                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
8971                                + ps.name + " changing from " + updatedPkg.codePathString
8972                                + " to " + scanFile);
8973                        updatedPkg.codePath = scanFile;
8974                        updatedPkg.codePathString = scanFile.toString();
8975                        updatedPkg.resourcePath = scanFile;
8976                        updatedPkg.resourcePathString = scanFile.toString();
8977                    }
8978                    updatedPkg.pkg = pkg;
8979                    updatedPkg.versionCode = pkg.mVersionCode;
8980
8981                    // Update the disabled system child packages to point to the package too.
8982                    final int childCount = updatedPkg.childPackageNames != null
8983                            ? updatedPkg.childPackageNames.size() : 0;
8984                    for (int i = 0; i < childCount; i++) {
8985                        String childPackageName = updatedPkg.childPackageNames.get(i);
8986                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
8987                                childPackageName);
8988                        if (updatedChildPkg != null) {
8989                            updatedChildPkg.pkg = pkg;
8990                            updatedChildPkg.versionCode = pkg.mVersionCode;
8991                        }
8992                    }
8993                } else {
8994                    // The current app on the system partition is better than
8995                    // what we have updated to on the data partition; switch
8996                    // back to the system partition version.
8997                    // At this point, its safely assumed that package installation for
8998                    // apps in system partition will go through. If not there won't be a working
8999                    // version of the app
9000                    // writer
9001                    synchronized (mPackages) {
9002                        // Just remove the loaded entries from package lists.
9003                        mPackages.remove(ps.name);
9004                    }
9005
9006                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
9007                            + " reverting from " + ps.codePathString
9008                            + ": new version " + pkg.mVersionCode
9009                            + " better than installed " + ps.versionCode);
9010
9011                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
9012                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
9013                    synchronized (mInstallLock) {
9014                        args.cleanUpResourcesLI();
9015                    }
9016                    synchronized (mPackages) {
9017                        mSettings.enableSystemPackageLPw(ps.name);
9018                    }
9019                    isUpdatedPkgBetter = true;
9020                }
9021            }
9022        }
9023
9024        String resourcePath = null;
9025        String baseResourcePath = null;
9026        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !isUpdatedPkgBetter) {
9027            if (ps != null && ps.resourcePathString != null) {
9028                resourcePath = ps.resourcePathString;
9029                baseResourcePath = ps.resourcePathString;
9030            } else {
9031                // Should not happen at all. Just log an error.
9032                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
9033            }
9034        } else {
9035            resourcePath = pkg.codePath;
9036            baseResourcePath = pkg.baseCodePath;
9037        }
9038
9039        // Set application objects path explicitly.
9040        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
9041        pkg.setApplicationInfoCodePath(pkg.codePath);
9042        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
9043        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
9044        pkg.setApplicationInfoResourcePath(resourcePath);
9045        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
9046        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
9047
9048        // throw an exception if we have an update to a system application, but, it's not more
9049        // recent than the package we've already scanned
9050        if (isUpdatedSystemPkg && !isUpdatedPkgBetter) {
9051            throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
9052                    + scanFile + " ignored: updated version " + ps.versionCode
9053                    + " better than this " + pkg.mVersionCode);
9054        }
9055
9056        if (isUpdatedPkg) {
9057            // An updated system app will not have the PARSE_IS_SYSTEM flag set
9058            // initially
9059            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
9060
9061            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
9062            // flag set initially
9063            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
9064                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
9065            }
9066        }
9067
9068        // Verify certificates against what was last scanned
9069        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
9070
9071        /*
9072         * A new system app appeared, but we already had a non-system one of the
9073         * same name installed earlier.
9074         */
9075        boolean shouldHideSystemApp = false;
9076        if (!isUpdatedPkg && ps != null
9077                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
9078            /*
9079             * Check to make sure the signatures match first. If they don't,
9080             * wipe the installed application and its data.
9081             */
9082            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
9083                    != PackageManager.SIGNATURE_MATCH) {
9084                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
9085                        + " signatures don't match existing userdata copy; removing");
9086                try (PackageFreezer freezer = freezePackage(pkg.packageName,
9087                        "scanPackageInternalLI")) {
9088                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
9089                }
9090                ps = null;
9091            } else {
9092                /*
9093                 * If the newly-added system app is an older version than the
9094                 * already installed version, hide it. It will be scanned later
9095                 * and re-added like an update.
9096                 */
9097                if (pkg.mVersionCode <= ps.versionCode) {
9098                    shouldHideSystemApp = true;
9099                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
9100                            + " but new version " + pkg.mVersionCode + " better than installed "
9101                            + ps.versionCode + "; hiding system");
9102                } else {
9103                    /*
9104                     * The newly found system app is a newer version that the
9105                     * one previously installed. Simply remove the
9106                     * already-installed application and replace it with our own
9107                     * while keeping the application data.
9108                     */
9109                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
9110                            + " reverting from " + ps.codePathString + ": new version "
9111                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
9112                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
9113                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
9114                    synchronized (mInstallLock) {
9115                        args.cleanUpResourcesLI();
9116                    }
9117                }
9118            }
9119        }
9120
9121        // The apk is forward locked (not public) if its code and resources
9122        // are kept in different files. (except for app in either system or
9123        // vendor path).
9124        // TODO grab this value from PackageSettings
9125        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9126            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
9127                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
9128            }
9129        }
9130
9131        final int userId = ((user == null) ? 0 : user.getIdentifier());
9132        if (ps != null && ps.getInstantApp(userId)) {
9133            scanFlags |= SCAN_AS_INSTANT_APP;
9134        }
9135
9136        // Note that we invoke the following method only if we are about to unpack an application
9137        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
9138                | SCAN_UPDATE_SIGNATURE, currentTime, user);
9139
9140        /*
9141         * If the system app should be overridden by a previously installed
9142         * data, hide the system app now and let the /data/app scan pick it up
9143         * again.
9144         */
9145        if (shouldHideSystemApp) {
9146            synchronized (mPackages) {
9147                mSettings.disableSystemPackageLPw(pkg.packageName, true);
9148            }
9149        }
9150
9151        return scannedPkg;
9152    }
9153
9154    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
9155        // Derive the new package synthetic package name
9156        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
9157                + pkg.staticSharedLibVersion);
9158    }
9159
9160    private static String fixProcessName(String defProcessName,
9161            String processName) {
9162        if (processName == null) {
9163            return defProcessName;
9164        }
9165        return processName;
9166    }
9167
9168    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
9169            throws PackageManagerException {
9170        if (pkgSetting.signatures.mSignatures != null) {
9171            // Already existing package. Make sure signatures match
9172            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
9173                    == PackageManager.SIGNATURE_MATCH;
9174            if (!match) {
9175                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
9176                        == PackageManager.SIGNATURE_MATCH;
9177            }
9178            if (!match) {
9179                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
9180                        == PackageManager.SIGNATURE_MATCH;
9181            }
9182            if (!match) {
9183                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
9184                        + pkg.packageName + " signatures do not match the "
9185                        + "previously installed version; ignoring!");
9186            }
9187        }
9188
9189        // Check for shared user signatures
9190        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
9191            // Already existing package. Make sure signatures match
9192            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
9193                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
9194            if (!match) {
9195                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
9196                        == PackageManager.SIGNATURE_MATCH;
9197            }
9198            if (!match) {
9199                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
9200                        == PackageManager.SIGNATURE_MATCH;
9201            }
9202            if (!match) {
9203                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
9204                        "Package " + pkg.packageName
9205                        + " has no signatures that match those in shared user "
9206                        + pkgSetting.sharedUser.name + "; ignoring!");
9207            }
9208        }
9209    }
9210
9211    /**
9212     * Enforces that only the system UID or root's UID can call a method exposed
9213     * via Binder.
9214     *
9215     * @param message used as message if SecurityException is thrown
9216     * @throws SecurityException if the caller is not system or root
9217     */
9218    private static final void enforceSystemOrRoot(String message) {
9219        final int uid = Binder.getCallingUid();
9220        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
9221            throw new SecurityException(message);
9222        }
9223    }
9224
9225    @Override
9226    public void performFstrimIfNeeded() {
9227        enforceSystemOrRoot("Only the system can request fstrim");
9228
9229        // Before everything else, see whether we need to fstrim.
9230        try {
9231            IStorageManager sm = PackageHelper.getStorageManager();
9232            if (sm != null) {
9233                boolean doTrim = false;
9234                final long interval = android.provider.Settings.Global.getLong(
9235                        mContext.getContentResolver(),
9236                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
9237                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
9238                if (interval > 0) {
9239                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
9240                    if (timeSinceLast > interval) {
9241                        doTrim = true;
9242                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
9243                                + "; running immediately");
9244                    }
9245                }
9246                if (doTrim) {
9247                    final boolean dexOptDialogShown;
9248                    synchronized (mPackages) {
9249                        dexOptDialogShown = mDexOptDialogShown;
9250                    }
9251                    if (!isFirstBoot() && dexOptDialogShown) {
9252                        try {
9253                            ActivityManager.getService().showBootMessage(
9254                                    mContext.getResources().getString(
9255                                            R.string.android_upgrading_fstrim), true);
9256                        } catch (RemoteException e) {
9257                        }
9258                    }
9259                    sm.runMaintenance();
9260                }
9261            } else {
9262                Slog.e(TAG, "storageManager service unavailable!");
9263            }
9264        } catch (RemoteException e) {
9265            // Can't happen; StorageManagerService is local
9266        }
9267    }
9268
9269    @Override
9270    public void updatePackagesIfNeeded() {
9271        enforceSystemOrRoot("Only the system can request package update");
9272
9273        // We need to re-extract after an OTA.
9274        boolean causeUpgrade = isUpgrade();
9275
9276        // First boot or factory reset.
9277        // Note: we also handle devices that are upgrading to N right now as if it is their
9278        //       first boot, as they do not have profile data.
9279        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
9280
9281        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
9282        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
9283
9284        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
9285            return;
9286        }
9287
9288        List<PackageParser.Package> pkgs;
9289        synchronized (mPackages) {
9290            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
9291        }
9292
9293        final long startTime = System.nanoTime();
9294        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
9295                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT),
9296                    false /* bootComplete */);
9297
9298        final int elapsedTimeSeconds =
9299                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
9300
9301        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
9302        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
9303        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
9304        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
9305        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
9306    }
9307
9308    /*
9309     * Return the prebuilt profile path given a package base code path.
9310     */
9311    private static String getPrebuildProfilePath(PackageParser.Package pkg) {
9312        return pkg.baseCodePath + ".prof";
9313    }
9314
9315    /**
9316     * Performs dexopt on the set of packages in {@code packages} and returns an int array
9317     * containing statistics about the invocation. The array consists of three elements,
9318     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
9319     * and {@code numberOfPackagesFailed}.
9320     */
9321    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
9322            String compilerFilter, boolean bootComplete) {
9323
9324        int numberOfPackagesVisited = 0;
9325        int numberOfPackagesOptimized = 0;
9326        int numberOfPackagesSkipped = 0;
9327        int numberOfPackagesFailed = 0;
9328        final int numberOfPackagesToDexopt = pkgs.size();
9329
9330        for (PackageParser.Package pkg : pkgs) {
9331            numberOfPackagesVisited++;
9332
9333            if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) {
9334                // Copy over initial preopt profiles since we won't get any JIT samples for methods
9335                // that are already compiled.
9336                File profileFile = new File(getPrebuildProfilePath(pkg));
9337                // Copy profile if it exists.
9338                if (profileFile.exists()) {
9339                    try {
9340                        // We could also do this lazily before calling dexopt in
9341                        // PackageDexOptimizer to prevent this happening on first boot. The issue
9342                        // is that we don't have a good way to say "do this only once".
9343                        if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
9344                                pkg.applicationInfo.uid, pkg.packageName)) {
9345                            Log.e(TAG, "Installer failed to copy system profile!");
9346                        }
9347                    } catch (Exception e) {
9348                        Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ",
9349                                e);
9350                    }
9351                }
9352            }
9353
9354            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
9355                if (DEBUG_DEXOPT) {
9356                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
9357                }
9358                numberOfPackagesSkipped++;
9359                continue;
9360            }
9361
9362            if (DEBUG_DEXOPT) {
9363                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
9364                        numberOfPackagesToDexopt + ": " + pkg.packageName);
9365            }
9366
9367            if (showDialog) {
9368                try {
9369                    ActivityManager.getService().showBootMessage(
9370                            mContext.getResources().getString(R.string.android_upgrading_apk,
9371                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
9372                } catch (RemoteException e) {
9373                }
9374                synchronized (mPackages) {
9375                    mDexOptDialogShown = true;
9376                }
9377            }
9378
9379            // If the OTA updates a system app which was previously preopted to a non-preopted state
9380            // the app might end up being verified at runtime. That's because by default the apps
9381            // are verify-profile but for preopted apps there's no profile.
9382            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
9383            // that before the OTA the app was preopted) the app gets compiled with a non-profile
9384            // filter (by default 'quicken').
9385            // Note that at this stage unused apps are already filtered.
9386            if (isSystemApp(pkg) &&
9387                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
9388                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
9389                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
9390            }
9391
9392            // checkProfiles is false to avoid merging profiles during boot which
9393            // might interfere with background compilation (b/28612421).
9394            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
9395            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
9396            // trade-off worth doing to save boot time work.
9397            int primaryDexOptStaus = performDexOptTraced(pkg.packageName,
9398                    false /* checkProfiles */,
9399                    compilerFilter,
9400                    false /* force */,
9401                    bootComplete,
9402                    false /* downgrade */);
9403
9404            boolean secondaryDexOptStatus = true;
9405            if (pkg.isSystemApp()) {
9406                // Only dexopt shared secondary dex files belonging to system apps to not slow down
9407                // too much boot after an OTA.
9408                secondaryDexOptStatus = mDexManager.dexoptSecondaryDex(pkg.packageName,
9409                        compilerFilter,
9410                        false /* force */,
9411                        true /* compileOnlySharedDex */,
9412                        false /* downgrade */);
9413            }
9414
9415            if (secondaryDexOptStatus) {
9416                switch (primaryDexOptStaus) {
9417                    case PackageDexOptimizer.DEX_OPT_PERFORMED:
9418                        numberOfPackagesOptimized++;
9419                        break;
9420                    case PackageDexOptimizer.DEX_OPT_SKIPPED:
9421                        numberOfPackagesSkipped++;
9422                        break;
9423                    case PackageDexOptimizer.DEX_OPT_FAILED:
9424                        numberOfPackagesFailed++;
9425                        break;
9426                    default:
9427                        Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus);
9428                        break;
9429                }
9430            } else {
9431                numberOfPackagesFailed++;
9432            }
9433        }
9434
9435        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
9436                numberOfPackagesFailed };
9437    }
9438
9439    @Override
9440    public void notifyPackageUse(String packageName, int reason) {
9441        synchronized (mPackages) {
9442            final int callingUid = Binder.getCallingUid();
9443            final int callingUserId = UserHandle.getUserId(callingUid);
9444            if (getInstantAppPackageName(callingUid) != null) {
9445                if (!isCallerSameApp(packageName, callingUid)) {
9446                    return;
9447                }
9448            } else {
9449                if (isInstantApp(packageName, callingUserId)) {
9450                    return;
9451                }
9452            }
9453            final PackageParser.Package p = mPackages.get(packageName);
9454            if (p == null) {
9455                return;
9456            }
9457            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9458        }
9459    }
9460
9461    @Override
9462    public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) {
9463        int userId = UserHandle.getCallingUserId();
9464        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9465        if (ai == null) {
9466            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9467                + loadingPackageName + ", user=" + userId);
9468            return;
9469        }
9470        mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId);
9471    }
9472
9473    @Override
9474    public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule,
9475            IDexModuleRegisterCallback callback) {
9476        int userId = UserHandle.getCallingUserId();
9477        ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId);
9478        DexManager.RegisterDexModuleResult result;
9479        if (ai == null) {
9480            Slog.w(TAG, "Registering a dex module for a package that does not exist for the" +
9481                     " calling user. package=" + packageName + ", user=" + userId);
9482            result = new DexManager.RegisterDexModuleResult(false, "Package not installed");
9483        } else {
9484            result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId);
9485        }
9486
9487        if (callback != null) {
9488            mHandler.post(() -> {
9489                try {
9490                    callback.onDexModuleRegistered(dexModulePath, result.success, result.message);
9491                } catch (RemoteException e) {
9492                    Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e);
9493                }
9494            });
9495        }
9496    }
9497
9498    @Override
9499    public boolean performDexOpt(String packageName,
9500            boolean checkProfiles, int compileReason, boolean force, boolean bootComplete,
9501            boolean downgrade) {
9502        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9503            return false;
9504        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9505            return false;
9506        }
9507        int dexoptStatus = performDexOptWithStatus(
9508              packageName, checkProfiles, compileReason, force, bootComplete,
9509              downgrade);
9510        return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9511    }
9512
9513    /**
9514     * Perform dexopt on the given package and return one of following result:
9515     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9516     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9517     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
9518     */
9519    /* package */ int performDexOptWithStatus(String packageName,
9520            boolean checkProfiles, int compileReason, boolean force, boolean bootComplete,
9521            boolean downgrade) {
9522        return performDexOptTraced(packageName, checkProfiles,
9523                getCompilerFilterForReason(compileReason), force, bootComplete, downgrade);
9524    }
9525
9526    @Override
9527    public boolean performDexOptMode(String packageName,
9528            boolean checkProfiles, String targetCompilerFilter, boolean force,
9529            boolean bootComplete) {
9530        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9531            return false;
9532        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9533            return false;
9534        }
9535        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
9536                targetCompilerFilter, force, bootComplete, false /* downgrade */);
9537        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9538    }
9539
9540    private int performDexOptTraced(String packageName,
9541                boolean checkProfiles, String targetCompilerFilter, boolean force,
9542                boolean bootComplete, boolean downgrade) {
9543        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9544        try {
9545            return performDexOptInternal(packageName, checkProfiles,
9546                    targetCompilerFilter, force, bootComplete, downgrade);
9547        } finally {
9548            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9549        }
9550    }
9551
9552    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
9553    // if the package can now be considered up to date for the given filter.
9554    private int performDexOptInternal(String packageName,
9555                boolean checkProfiles, String targetCompilerFilter, boolean force,
9556                boolean bootComplete, boolean downgrade) {
9557        PackageParser.Package p;
9558        synchronized (mPackages) {
9559            p = mPackages.get(packageName);
9560            if (p == null) {
9561                // Package could not be found. Report failure.
9562                return PackageDexOptimizer.DEX_OPT_FAILED;
9563            }
9564            mPackageUsage.maybeWriteAsync(mPackages);
9565            mCompilerStats.maybeWriteAsync();
9566        }
9567        long callingId = Binder.clearCallingIdentity();
9568        try {
9569            synchronized (mInstallLock) {
9570                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
9571                        targetCompilerFilter, force, bootComplete, downgrade);
9572            }
9573        } finally {
9574            Binder.restoreCallingIdentity(callingId);
9575        }
9576    }
9577
9578    public ArraySet<String> getOptimizablePackages() {
9579        ArraySet<String> pkgs = new ArraySet<String>();
9580        synchronized (mPackages) {
9581            for (PackageParser.Package p : mPackages.values()) {
9582                if (PackageDexOptimizer.canOptimizePackage(p)) {
9583                    pkgs.add(p.packageName);
9584                }
9585            }
9586        }
9587        return pkgs;
9588    }
9589
9590    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
9591            boolean checkProfiles, String targetCompilerFilter,
9592            boolean force, boolean bootComplete, boolean downgrade) {
9593        // Select the dex optimizer based on the force parameter.
9594        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
9595        //       allocate an object here.
9596        PackageDexOptimizer pdo = force
9597                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
9598                : mPackageDexOptimizer;
9599
9600        // Dexopt all dependencies first. Note: we ignore the return value and march on
9601        // on errors.
9602        // Note that we are going to call performDexOpt on those libraries as many times as
9603        // they are referenced in packages. When we do a batch of performDexOpt (for example
9604        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
9605        // and the first package that uses the library will dexopt it. The
9606        // others will see that the compiled code for the library is up to date.
9607        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
9608        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
9609        if (!deps.isEmpty()) {
9610            for (PackageParser.Package depPackage : deps) {
9611                // TODO: Analyze and investigate if we (should) profile libraries.
9612                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
9613                        false /* checkProfiles */,
9614                        targetCompilerFilter,
9615                        getOrCreateCompilerPackageStats(depPackage),
9616                        true /* isUsedByOtherApps */,
9617                        bootComplete,
9618                        downgrade);
9619            }
9620        }
9621        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
9622                targetCompilerFilter, getOrCreateCompilerPackageStats(p),
9623                mDexManager.isUsedByOtherApps(p.packageName), bootComplete, downgrade);
9624    }
9625
9626    // Performs dexopt on the used secondary dex files belonging to the given package.
9627    // Returns true if all dex files were process successfully (which could mean either dexopt or
9628    // skip). Returns false if any of the files caused errors.
9629    @Override
9630    public boolean performDexOptSecondary(String packageName, String compilerFilter,
9631            boolean force) {
9632        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9633            return false;
9634        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9635            return false;
9636        }
9637        return mDexManager.dexoptSecondaryDex(packageName, compilerFilter, force,
9638                false /* compileOnlySharedDex */, false /* downgrade */);
9639    }
9640
9641    public boolean performDexOptSecondary(String packageName, int compileReason,
9642            boolean force, boolean downgrade) {
9643        return mDexManager.dexoptSecondaryDex(packageName, compileReason, force, downgrade);
9644    }
9645
9646    /**
9647     * Reconcile the information we have about the secondary dex files belonging to
9648     * {@code packagName} and the actual dex files. For all dex files that were
9649     * deleted, update the internal records and delete the generated oat files.
9650     */
9651    @Override
9652    public void reconcileSecondaryDexFiles(String packageName) {
9653        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9654            return;
9655        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9656            return;
9657        }
9658        mDexManager.reconcileSecondaryDexFiles(packageName);
9659    }
9660
9661    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
9662    // a reference there.
9663    /*package*/ DexManager getDexManager() {
9664        return mDexManager;
9665    }
9666
9667    /**
9668     * Execute the background dexopt job immediately.
9669     */
9670    @Override
9671    public boolean runBackgroundDexoptJob() {
9672        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9673            return false;
9674        }
9675        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
9676    }
9677
9678    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
9679        if (p.usesLibraries != null || p.usesOptionalLibraries != null
9680                || p.usesStaticLibraries != null) {
9681            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
9682            Set<String> collectedNames = new HashSet<>();
9683            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
9684
9685            retValue.remove(p);
9686
9687            return retValue;
9688        } else {
9689            return Collections.emptyList();
9690        }
9691    }
9692
9693    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
9694            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9695        if (!collectedNames.contains(p.packageName)) {
9696            collectedNames.add(p.packageName);
9697            collected.add(p);
9698
9699            if (p.usesLibraries != null) {
9700                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
9701                        null, collected, collectedNames);
9702            }
9703            if (p.usesOptionalLibraries != null) {
9704                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
9705                        null, collected, collectedNames);
9706            }
9707            if (p.usesStaticLibraries != null) {
9708                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
9709                        p.usesStaticLibrariesVersions, collected, collectedNames);
9710            }
9711        }
9712    }
9713
9714    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
9715            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9716        final int libNameCount = libs.size();
9717        for (int i = 0; i < libNameCount; i++) {
9718            String libName = libs.get(i);
9719            int version = (versions != null && versions.length == libNameCount)
9720                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
9721            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
9722            if (libPkg != null) {
9723                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
9724            }
9725        }
9726    }
9727
9728    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
9729        synchronized (mPackages) {
9730            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
9731            if (libEntry != null) {
9732                return mPackages.get(libEntry.apk);
9733            }
9734            return null;
9735        }
9736    }
9737
9738    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
9739        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9740        if (versionedLib == null) {
9741            return null;
9742        }
9743        return versionedLib.get(version);
9744    }
9745
9746    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
9747        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9748                pkg.staticSharedLibName);
9749        if (versionedLib == null) {
9750            return null;
9751        }
9752        int previousLibVersion = -1;
9753        final int versionCount = versionedLib.size();
9754        for (int i = 0; i < versionCount; i++) {
9755            final int libVersion = versionedLib.keyAt(i);
9756            if (libVersion < pkg.staticSharedLibVersion) {
9757                previousLibVersion = Math.max(previousLibVersion, libVersion);
9758            }
9759        }
9760        if (previousLibVersion >= 0) {
9761            return versionedLib.get(previousLibVersion);
9762        }
9763        return null;
9764    }
9765
9766    public void shutdown() {
9767        mPackageUsage.writeNow(mPackages);
9768        mCompilerStats.writeNow();
9769    }
9770
9771    @Override
9772    public void dumpProfiles(String packageName) {
9773        PackageParser.Package pkg;
9774        synchronized (mPackages) {
9775            pkg = mPackages.get(packageName);
9776            if (pkg == null) {
9777                throw new IllegalArgumentException("Unknown package: " + packageName);
9778            }
9779        }
9780        /* Only the shell, root, or the app user should be able to dump profiles. */
9781        int callingUid = Binder.getCallingUid();
9782        if (callingUid != Process.SHELL_UID &&
9783            callingUid != Process.ROOT_UID &&
9784            callingUid != pkg.applicationInfo.uid) {
9785            throw new SecurityException("dumpProfiles");
9786        }
9787
9788        synchronized (mInstallLock) {
9789            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
9790            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
9791            try {
9792                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
9793                String codePaths = TextUtils.join(";", allCodePaths);
9794                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
9795            } catch (InstallerException e) {
9796                Slog.w(TAG, "Failed to dump profiles", e);
9797            }
9798            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9799        }
9800    }
9801
9802    @Override
9803    public void forceDexOpt(String packageName) {
9804        enforceSystemOrRoot("forceDexOpt");
9805
9806        PackageParser.Package pkg;
9807        synchronized (mPackages) {
9808            pkg = mPackages.get(packageName);
9809            if (pkg == null) {
9810                throw new IllegalArgumentException("Unknown package: " + packageName);
9811            }
9812        }
9813
9814        synchronized (mInstallLock) {
9815            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9816
9817            // Whoever is calling forceDexOpt wants a compiled package.
9818            // Don't use profiles since that may cause compilation to be skipped.
9819            final int res = performDexOptInternalWithDependenciesLI(pkg,
9820                    false /* checkProfiles */, getDefaultCompilerFilter(),
9821                    true /* force */,
9822                    true /* bootComplete */,
9823                    false /* downgrade */);
9824
9825            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9826            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
9827                throw new IllegalStateException("Failed to dexopt: " + res);
9828            }
9829        }
9830    }
9831
9832    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
9833        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
9834            Slog.w(TAG, "Unable to update from " + oldPkg.name
9835                    + " to " + newPkg.packageName
9836                    + ": old package not in system partition");
9837            return false;
9838        } else if (mPackages.get(oldPkg.name) != null) {
9839            Slog.w(TAG, "Unable to update from " + oldPkg.name
9840                    + " to " + newPkg.packageName
9841                    + ": old package still exists");
9842            return false;
9843        }
9844        return true;
9845    }
9846
9847    void removeCodePathLI(File codePath) {
9848        if (codePath.isDirectory()) {
9849            try {
9850                mInstaller.rmPackageDir(codePath.getAbsolutePath());
9851            } catch (InstallerException e) {
9852                Slog.w(TAG, "Failed to remove code path", e);
9853            }
9854        } else {
9855            codePath.delete();
9856        }
9857    }
9858
9859    private int[] resolveUserIds(int userId) {
9860        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
9861    }
9862
9863    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9864        if (pkg == null) {
9865            Slog.wtf(TAG, "Package was null!", new Throwable());
9866            return;
9867        }
9868        clearAppDataLeafLIF(pkg, userId, flags);
9869        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9870        for (int i = 0; i < childCount; i++) {
9871            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9872        }
9873    }
9874
9875    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9876        final PackageSetting ps;
9877        synchronized (mPackages) {
9878            ps = mSettings.mPackages.get(pkg.packageName);
9879        }
9880        for (int realUserId : resolveUserIds(userId)) {
9881            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9882            try {
9883                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9884                        ceDataInode);
9885            } catch (InstallerException e) {
9886                Slog.w(TAG, String.valueOf(e));
9887            }
9888        }
9889    }
9890
9891    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9892        if (pkg == null) {
9893            Slog.wtf(TAG, "Package was null!", new Throwable());
9894            return;
9895        }
9896        destroyAppDataLeafLIF(pkg, userId, flags);
9897        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9898        for (int i = 0; i < childCount; i++) {
9899            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9900        }
9901    }
9902
9903    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9904        final PackageSetting ps;
9905        synchronized (mPackages) {
9906            ps = mSettings.mPackages.get(pkg.packageName);
9907        }
9908        for (int realUserId : resolveUserIds(userId)) {
9909            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9910            try {
9911                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9912                        ceDataInode);
9913            } catch (InstallerException e) {
9914                Slog.w(TAG, String.valueOf(e));
9915            }
9916            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
9917        }
9918    }
9919
9920    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
9921        if (pkg == null) {
9922            Slog.wtf(TAG, "Package was null!", new Throwable());
9923            return;
9924        }
9925        destroyAppProfilesLeafLIF(pkg);
9926        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9927        for (int i = 0; i < childCount; i++) {
9928            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
9929        }
9930    }
9931
9932    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
9933        try {
9934            mInstaller.destroyAppProfiles(pkg.packageName);
9935        } catch (InstallerException e) {
9936            Slog.w(TAG, String.valueOf(e));
9937        }
9938    }
9939
9940    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
9941        if (pkg == null) {
9942            Slog.wtf(TAG, "Package was null!", new Throwable());
9943            return;
9944        }
9945        clearAppProfilesLeafLIF(pkg);
9946        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9947        for (int i = 0; i < childCount; i++) {
9948            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
9949        }
9950    }
9951
9952    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
9953        try {
9954            mInstaller.clearAppProfiles(pkg.packageName);
9955        } catch (InstallerException e) {
9956            Slog.w(TAG, String.valueOf(e));
9957        }
9958    }
9959
9960    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
9961            long lastUpdateTime) {
9962        // Set parent install/update time
9963        PackageSetting ps = (PackageSetting) pkg.mExtras;
9964        if (ps != null) {
9965            ps.firstInstallTime = firstInstallTime;
9966            ps.lastUpdateTime = lastUpdateTime;
9967        }
9968        // Set children install/update time
9969        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9970        for (int i = 0; i < childCount; i++) {
9971            PackageParser.Package childPkg = pkg.childPackages.get(i);
9972            ps = (PackageSetting) childPkg.mExtras;
9973            if (ps != null) {
9974                ps.firstInstallTime = firstInstallTime;
9975                ps.lastUpdateTime = lastUpdateTime;
9976            }
9977        }
9978    }
9979
9980    private void addSharedLibraryLPr(Set<String> usesLibraryFiles,
9981            SharedLibraryEntry file,
9982            PackageParser.Package changingLib) {
9983        if (file.path != null) {
9984            usesLibraryFiles.add(file.path);
9985            return;
9986        }
9987        PackageParser.Package p = mPackages.get(file.apk);
9988        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
9989            // If we are doing this while in the middle of updating a library apk,
9990            // then we need to make sure to use that new apk for determining the
9991            // dependencies here.  (We haven't yet finished committing the new apk
9992            // to the package manager state.)
9993            if (p == null || p.packageName.equals(changingLib.packageName)) {
9994                p = changingLib;
9995            }
9996        }
9997        if (p != null) {
9998            usesLibraryFiles.addAll(p.getAllCodePaths());
9999            if (p.usesLibraryFiles != null) {
10000                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
10001            }
10002        }
10003    }
10004
10005    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
10006            PackageParser.Package changingLib) throws PackageManagerException {
10007        if (pkg == null) {
10008            return;
10009        }
10010        // The collection used here must maintain the order of addition (so
10011        // that libraries are searched in the correct order) and must have no
10012        // duplicates.
10013        Set<String> usesLibraryFiles = null;
10014        if (pkg.usesLibraries != null) {
10015            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
10016                    null, null, pkg.packageName, changingLib, true, null);
10017        }
10018        if (pkg.usesStaticLibraries != null) {
10019            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
10020                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
10021                    pkg.packageName, changingLib, true, usesLibraryFiles);
10022        }
10023        if (pkg.usesOptionalLibraries != null) {
10024            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
10025                    null, null, pkg.packageName, changingLib, false, usesLibraryFiles);
10026        }
10027        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
10028            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
10029        } else {
10030            pkg.usesLibraryFiles = null;
10031        }
10032    }
10033
10034    private Set<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
10035            @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests,
10036            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
10037            boolean required, @Nullable Set<String> outUsedLibraries)
10038            throws PackageManagerException {
10039        final int libCount = requestedLibraries.size();
10040        for (int i = 0; i < libCount; i++) {
10041            final String libName = requestedLibraries.get(i);
10042            final int libVersion = requiredVersions != null ? requiredVersions[i]
10043                    : SharedLibraryInfo.VERSION_UNDEFINED;
10044            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
10045            if (libEntry == null) {
10046                if (required) {
10047                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10048                            "Package " + packageName + " requires unavailable shared library "
10049                                    + libName + "; failing!");
10050                } else if (DEBUG_SHARED_LIBRARIES) {
10051                    Slog.i(TAG, "Package " + packageName
10052                            + " desires unavailable shared library "
10053                            + libName + "; ignoring!");
10054                }
10055            } else {
10056                if (requiredVersions != null && requiredCertDigests != null) {
10057                    if (libEntry.info.getVersion() != requiredVersions[i]) {
10058                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10059                            "Package " + packageName + " requires unavailable static shared"
10060                                    + " library " + libName + " version "
10061                                    + libEntry.info.getVersion() + "; failing!");
10062                    }
10063
10064                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
10065                    if (libPkg == null) {
10066                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10067                                "Package " + packageName + " requires unavailable static shared"
10068                                        + " library; failing!");
10069                    }
10070
10071                    String expectedCertDigest = requiredCertDigests[i];
10072                    String libCertDigest = PackageUtils.computeCertSha256Digest(
10073                                libPkg.mSignatures[0]);
10074                    if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) {
10075                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10076                                "Package " + packageName + " requires differently signed" +
10077                                        " static shared library; failing!");
10078                    }
10079                }
10080
10081                if (outUsedLibraries == null) {
10082                    // Use LinkedHashSet to preserve the order of files added to
10083                    // usesLibraryFiles while eliminating duplicates.
10084                    outUsedLibraries = new LinkedHashSet<>();
10085                }
10086                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
10087            }
10088        }
10089        return outUsedLibraries;
10090    }
10091
10092    private static boolean hasString(List<String> list, List<String> which) {
10093        if (list == null) {
10094            return false;
10095        }
10096        for (int i=list.size()-1; i>=0; i--) {
10097            for (int j=which.size()-1; j>=0; j--) {
10098                if (which.get(j).equals(list.get(i))) {
10099                    return true;
10100                }
10101            }
10102        }
10103        return false;
10104    }
10105
10106    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
10107            PackageParser.Package changingPkg) {
10108        ArrayList<PackageParser.Package> res = null;
10109        for (PackageParser.Package pkg : mPackages.values()) {
10110            if (changingPkg != null
10111                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
10112                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
10113                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
10114                            changingPkg.staticSharedLibName)) {
10115                return null;
10116            }
10117            if (res == null) {
10118                res = new ArrayList<>();
10119            }
10120            res.add(pkg);
10121            try {
10122                updateSharedLibrariesLPr(pkg, changingPkg);
10123            } catch (PackageManagerException e) {
10124                // If a system app update or an app and a required lib missing we
10125                // delete the package and for updated system apps keep the data as
10126                // it is better for the user to reinstall than to be in an limbo
10127                // state. Also libs disappearing under an app should never happen
10128                // - just in case.
10129                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
10130                    final int flags = pkg.isUpdatedSystemApp()
10131                            ? PackageManager.DELETE_KEEP_DATA : 0;
10132                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
10133                            flags , null, true, null);
10134                }
10135                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
10136            }
10137        }
10138        return res;
10139    }
10140
10141    /**
10142     * Derive the value of the {@code cpuAbiOverride} based on the provided
10143     * value and an optional stored value from the package settings.
10144     */
10145    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
10146        String cpuAbiOverride = null;
10147
10148        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
10149            cpuAbiOverride = null;
10150        } else if (abiOverride != null) {
10151            cpuAbiOverride = abiOverride;
10152        } else if (settings != null) {
10153            cpuAbiOverride = settings.cpuAbiOverrideString;
10154        }
10155
10156        return cpuAbiOverride;
10157    }
10158
10159    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
10160            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
10161                    throws PackageManagerException {
10162        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
10163        // If the package has children and this is the first dive in the function
10164        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
10165        // whether all packages (parent and children) would be successfully scanned
10166        // before the actual scan since scanning mutates internal state and we want
10167        // to atomically install the package and its children.
10168        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10169            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
10170                scanFlags |= SCAN_CHECK_ONLY;
10171            }
10172        } else {
10173            scanFlags &= ~SCAN_CHECK_ONLY;
10174        }
10175
10176        final PackageParser.Package scannedPkg;
10177        try {
10178            // Scan the parent
10179            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
10180            // Scan the children
10181            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10182            for (int i = 0; i < childCount; i++) {
10183                PackageParser.Package childPkg = pkg.childPackages.get(i);
10184                scanPackageLI(childPkg, policyFlags,
10185                        scanFlags, currentTime, user);
10186            }
10187        } finally {
10188            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10189        }
10190
10191        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10192            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
10193        }
10194
10195        return scannedPkg;
10196    }
10197
10198    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
10199            int scanFlags, long currentTime, @Nullable UserHandle user)
10200                    throws PackageManagerException {
10201        boolean success = false;
10202        try {
10203            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
10204                    currentTime, user);
10205            success = true;
10206            return res;
10207        } finally {
10208            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
10209                // DELETE_DATA_ON_FAILURES is only used by frozen paths
10210                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
10211                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
10212                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
10213            }
10214        }
10215    }
10216
10217    /**
10218     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
10219     */
10220    private static boolean apkHasCode(String fileName) {
10221        StrictJarFile jarFile = null;
10222        try {
10223            jarFile = new StrictJarFile(fileName,
10224                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
10225            return jarFile.findEntry("classes.dex") != null;
10226        } catch (IOException ignore) {
10227        } finally {
10228            try {
10229                if (jarFile != null) {
10230                    jarFile.close();
10231                }
10232            } catch (IOException ignore) {}
10233        }
10234        return false;
10235    }
10236
10237    /**
10238     * Enforces code policy for the package. This ensures that if an APK has
10239     * declared hasCode="true" in its manifest that the APK actually contains
10240     * code.
10241     *
10242     * @throws PackageManagerException If bytecode could not be found when it should exist
10243     */
10244    private static void assertCodePolicy(PackageParser.Package pkg)
10245            throws PackageManagerException {
10246        final boolean shouldHaveCode =
10247                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10248        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10249            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10250                    "Package " + pkg.baseCodePath + " code is missing");
10251        }
10252
10253        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10254            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10255                final boolean splitShouldHaveCode =
10256                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10257                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10258                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10259                            "Package " + pkg.splitCodePaths[i] + " code is missing");
10260                }
10261            }
10262        }
10263    }
10264
10265    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
10266            final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
10267                    throws PackageManagerException {
10268        if (DEBUG_PACKAGE_SCANNING) {
10269            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10270                Log.d(TAG, "Scanning package " + pkg.packageName);
10271        }
10272
10273        applyPolicy(pkg, policyFlags);
10274
10275        assertPackageIsValid(pkg, policyFlags, scanFlags);
10276
10277        if (Build.IS_DEBUGGABLE &&
10278                pkg.isPrivilegedApp() &&
10279                !SystemProperties.getBoolean("pm.dexopt.priv-apps", true)) {
10280            PackageManagerServiceUtils.logPackageHasUncompressedCode(pkg);
10281        }
10282
10283        // Initialize package source and resource directories
10284        final File scanFile = new File(pkg.codePath);
10285        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10286        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10287
10288        SharedUserSetting suid = null;
10289        PackageSetting pkgSetting = null;
10290
10291        // Getting the package setting may have a side-effect, so if we
10292        // are only checking if scan would succeed, stash a copy of the
10293        // old setting to restore at the end.
10294        PackageSetting nonMutatedPs = null;
10295
10296        // We keep references to the derived CPU Abis from settings in oder to reuse
10297        // them in the case where we're not upgrading or booting for the first time.
10298        String primaryCpuAbiFromSettings = null;
10299        String secondaryCpuAbiFromSettings = null;
10300
10301        // writer
10302        synchronized (mPackages) {
10303            if (pkg.mSharedUserId != null) {
10304                // SIDE EFFECTS; may potentially allocate a new shared user
10305                suid = mSettings.getSharedUserLPw(
10306                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
10307                if (DEBUG_PACKAGE_SCANNING) {
10308                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10309                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
10310                                + "): packages=" + suid.packages);
10311                }
10312            }
10313
10314            // Check if we are renaming from an original package name.
10315            PackageSetting origPackage = null;
10316            String realName = null;
10317            if (pkg.mOriginalPackages != null) {
10318                // This package may need to be renamed to a previously
10319                // installed name.  Let's check on that...
10320                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
10321                if (pkg.mOriginalPackages.contains(renamed)) {
10322                    // This package had originally been installed as the
10323                    // original name, and we have already taken care of
10324                    // transitioning to the new one.  Just update the new
10325                    // one to continue using the old name.
10326                    realName = pkg.mRealPackage;
10327                    if (!pkg.packageName.equals(renamed)) {
10328                        // Callers into this function may have already taken
10329                        // care of renaming the package; only do it here if
10330                        // it is not already done.
10331                        pkg.setPackageName(renamed);
10332                    }
10333                } else {
10334                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
10335                        if ((origPackage = mSettings.getPackageLPr(
10336                                pkg.mOriginalPackages.get(i))) != null) {
10337                            // We do have the package already installed under its
10338                            // original name...  should we use it?
10339                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
10340                                // New package is not compatible with original.
10341                                origPackage = null;
10342                                continue;
10343                            } else if (origPackage.sharedUser != null) {
10344                                // Make sure uid is compatible between packages.
10345                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
10346                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
10347                                            + " to " + pkg.packageName + ": old uid "
10348                                            + origPackage.sharedUser.name
10349                                            + " differs from " + pkg.mSharedUserId);
10350                                    origPackage = null;
10351                                    continue;
10352                                }
10353                                // TODO: Add case when shared user id is added [b/28144775]
10354                            } else {
10355                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10356                                        + pkg.packageName + " to old name " + origPackage.name);
10357                            }
10358                            break;
10359                        }
10360                    }
10361                }
10362            }
10363
10364            if (mTransferedPackages.contains(pkg.packageName)) {
10365                Slog.w(TAG, "Package " + pkg.packageName
10366                        + " was transferred to another, but its .apk remains");
10367            }
10368
10369            // See comments in nonMutatedPs declaration
10370            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10371                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10372                if (foundPs != null) {
10373                    nonMutatedPs = new PackageSetting(foundPs);
10374                }
10375            }
10376
10377            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
10378                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10379                if (foundPs != null) {
10380                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
10381                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
10382                }
10383            }
10384
10385            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
10386            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
10387                PackageManagerService.reportSettingsProblem(Log.WARN,
10388                        "Package " + pkg.packageName + " shared user changed from "
10389                                + (pkgSetting.sharedUser != null
10390                                        ? pkgSetting.sharedUser.name : "<nothing>")
10391                                + " to "
10392                                + (suid != null ? suid.name : "<nothing>")
10393                                + "; replacing with new");
10394                pkgSetting = null;
10395            }
10396            final PackageSetting oldPkgSetting =
10397                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
10398            final PackageSetting disabledPkgSetting =
10399                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
10400
10401            String[] usesStaticLibraries = null;
10402            if (pkg.usesStaticLibraries != null) {
10403                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10404                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10405            }
10406
10407            if (pkgSetting == null) {
10408                final String parentPackageName = (pkg.parentPackage != null)
10409                        ? pkg.parentPackage.packageName : null;
10410                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10411                // REMOVE SharedUserSetting from method; update in a separate call
10412                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
10413                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
10414                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
10415                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
10416                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
10417                        true /*allowInstall*/, instantApp, parentPackageName,
10418                        pkg.getChildPackageNames(), UserManagerService.getInstance(),
10419                        usesStaticLibraries, pkg.usesStaticLibrariesVersions);
10420                // SIDE EFFECTS; updates system state; move elsewhere
10421                if (origPackage != null) {
10422                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
10423                }
10424                mSettings.addUserToSettingLPw(pkgSetting);
10425            } else {
10426                // REMOVE SharedUserSetting from method; update in a separate call.
10427                //
10428                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10429                // secondaryCpuAbi are not known at this point so we always update them
10430                // to null here, only to reset them at a later point.
10431                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
10432                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
10433                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
10434                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
10435                        UserManagerService.getInstance(), usesStaticLibraries,
10436                        pkg.usesStaticLibrariesVersions);
10437            }
10438            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
10439            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10440
10441            // SIDE EFFECTS; modifies system state; move elsewhere
10442            if (pkgSetting.origPackage != null) {
10443                // If we are first transitioning from an original package,
10444                // fix up the new package's name now.  We need to do this after
10445                // looking up the package under its new name, so getPackageLP
10446                // can take care of fiddling things correctly.
10447                pkg.setPackageName(origPackage.name);
10448
10449                // File a report about this.
10450                String msg = "New package " + pkgSetting.realName
10451                        + " renamed to replace old package " + pkgSetting.name;
10452                reportSettingsProblem(Log.WARN, msg);
10453
10454                // Make a note of it.
10455                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10456                    mTransferedPackages.add(origPackage.name);
10457                }
10458
10459                // No longer need to retain this.
10460                pkgSetting.origPackage = null;
10461            }
10462
10463            // SIDE EFFECTS; modifies system state; move elsewhere
10464            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
10465                // Make a note of it.
10466                mTransferedPackages.add(pkg.packageName);
10467            }
10468
10469            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
10470                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10471            }
10472
10473            if ((scanFlags & SCAN_BOOTING) == 0
10474                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10475                // Check all shared libraries and map to their actual file path.
10476                // We only do this here for apps not on a system dir, because those
10477                // are the only ones that can fail an install due to this.  We
10478                // will take care of the system apps by updating all of their
10479                // library paths after the scan is done. Also during the initial
10480                // scan don't update any libs as we do this wholesale after all
10481                // apps are scanned to avoid dependency based scanning.
10482                updateSharedLibrariesLPr(pkg, null);
10483            }
10484
10485            if (mFoundPolicyFile) {
10486                SELinuxMMAC.assignSeInfoValue(pkg);
10487            }
10488            pkg.applicationInfo.uid = pkgSetting.appId;
10489            pkg.mExtras = pkgSetting;
10490
10491
10492            // Static shared libs have same package with different versions where
10493            // we internally use a synthetic package name to allow multiple versions
10494            // of the same package, therefore we need to compare signatures against
10495            // the package setting for the latest library version.
10496            PackageSetting signatureCheckPs = pkgSetting;
10497            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10498                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10499                if (libraryEntry != null) {
10500                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10501                }
10502            }
10503
10504            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
10505                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
10506                    // We just determined the app is signed correctly, so bring
10507                    // over the latest parsed certs.
10508                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10509                } else {
10510                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10511                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10512                                "Package " + pkg.packageName + " upgrade keys do not match the "
10513                                + "previously installed version");
10514                    } else {
10515                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
10516                        String msg = "System package " + pkg.packageName
10517                                + " signature changed; retaining data.";
10518                        reportSettingsProblem(Log.WARN, msg);
10519                    }
10520                }
10521            } else {
10522                try {
10523                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
10524                    verifySignaturesLP(signatureCheckPs, pkg);
10525                    // We just determined the app is signed correctly, so bring
10526                    // over the latest parsed certs.
10527                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10528                } catch (PackageManagerException e) {
10529                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10530                        throw e;
10531                    }
10532                    // The signature has changed, but this package is in the system
10533                    // image...  let's recover!
10534                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10535                    // However...  if this package is part of a shared user, but it
10536                    // doesn't match the signature of the shared user, let's fail.
10537                    // What this means is that you can't change the signatures
10538                    // associated with an overall shared user, which doesn't seem all
10539                    // that unreasonable.
10540                    if (signatureCheckPs.sharedUser != null) {
10541                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
10542                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
10543                            throw new PackageManagerException(
10544                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10545                                    "Signature mismatch for shared user: "
10546                                            + pkgSetting.sharedUser);
10547                        }
10548                    }
10549                    // File a report about this.
10550                    String msg = "System package " + pkg.packageName
10551                            + " signature changed; retaining data.";
10552                    reportSettingsProblem(Log.WARN, msg);
10553                }
10554            }
10555
10556            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
10557                // This package wants to adopt ownership of permissions from
10558                // another package.
10559                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
10560                    final String origName = pkg.mAdoptPermissions.get(i);
10561                    final PackageSetting orig = mSettings.getPackageLPr(origName);
10562                    if (orig != null) {
10563                        if (verifyPackageUpdateLPr(orig, pkg)) {
10564                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
10565                                    + pkg.packageName);
10566                            // SIDE EFFECTS; updates permissions system state; move elsewhere
10567                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
10568                        }
10569                    }
10570                }
10571            }
10572        }
10573
10574        pkg.applicationInfo.processName = fixProcessName(
10575                pkg.applicationInfo.packageName,
10576                pkg.applicationInfo.processName);
10577
10578        if (pkg != mPlatformPackage) {
10579            // Get all of our default paths setup
10580            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10581        }
10582
10583        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10584
10585        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10586            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
10587                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10588                final boolean extractNativeLibs = !pkg.isLibrary();
10589                derivePackageAbi(pkg, scanFile, cpuAbiOverride, extractNativeLibs,
10590                        mAppLib32InstallDir);
10591                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10592
10593                // Some system apps still use directory structure for native libraries
10594                // in which case we might end up not detecting abi solely based on apk
10595                // structure. Try to detect abi based on directory structure.
10596                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
10597                        pkg.applicationInfo.primaryCpuAbi == null) {
10598                    setBundledAppAbisAndRoots(pkg, pkgSetting);
10599                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10600                }
10601            } else {
10602                // This is not a first boot or an upgrade, don't bother deriving the
10603                // ABI during the scan. Instead, trust the value that was stored in the
10604                // package setting.
10605                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
10606                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
10607
10608                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10609
10610                if (DEBUG_ABI_SELECTION) {
10611                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
10612                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
10613                        pkg.applicationInfo.secondaryCpuAbi);
10614                }
10615            }
10616        } else {
10617            if ((scanFlags & SCAN_MOVE) != 0) {
10618                // We haven't run dex-opt for this move (since we've moved the compiled output too)
10619                // but we already have this packages package info in the PackageSetting. We just
10620                // use that and derive the native library path based on the new codepath.
10621                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
10622                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
10623            }
10624
10625            // Set native library paths again. For moves, the path will be updated based on the
10626            // ABIs we've determined above. For non-moves, the path will be updated based on the
10627            // ABIs we determined during compilation, but the path will depend on the final
10628            // package path (after the rename away from the stage path).
10629            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10630        }
10631
10632        // This is a special case for the "system" package, where the ABI is
10633        // dictated by the zygote configuration (and init.rc). We should keep track
10634        // of this ABI so that we can deal with "normal" applications that run under
10635        // the same UID correctly.
10636        if (mPlatformPackage == pkg) {
10637            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
10638                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
10639        }
10640
10641        // If there's a mismatch between the abi-override in the package setting
10642        // and the abiOverride specified for the install. Warn about this because we
10643        // would've already compiled the app without taking the package setting into
10644        // account.
10645        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
10646            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
10647                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
10648                        " for package " + pkg.packageName);
10649            }
10650        }
10651
10652        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10653        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10654        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
10655
10656        // Copy the derived override back to the parsed package, so that we can
10657        // update the package settings accordingly.
10658        pkg.cpuAbiOverride = cpuAbiOverride;
10659
10660        if (DEBUG_ABI_SELECTION) {
10661            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
10662                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
10663                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
10664        }
10665
10666        // Push the derived path down into PackageSettings so we know what to
10667        // clean up at uninstall time.
10668        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
10669
10670        if (DEBUG_ABI_SELECTION) {
10671            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
10672                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
10673                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
10674        }
10675
10676        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
10677        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
10678            // We don't do this here during boot because we can do it all
10679            // at once after scanning all existing packages.
10680            //
10681            // We also do this *before* we perform dexopt on this package, so that
10682            // we can avoid redundant dexopts, and also to make sure we've got the
10683            // code and package path correct.
10684            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
10685        }
10686
10687        if (mFactoryTest && pkg.requestedPermissions.contains(
10688                android.Manifest.permission.FACTORY_TEST)) {
10689            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
10690        }
10691
10692        if (isSystemApp(pkg)) {
10693            pkgSetting.isOrphaned = true;
10694        }
10695
10696        // Take care of first install / last update times.
10697        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
10698        if (currentTime != 0) {
10699            if (pkgSetting.firstInstallTime == 0) {
10700                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
10701            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
10702                pkgSetting.lastUpdateTime = currentTime;
10703            }
10704        } else if (pkgSetting.firstInstallTime == 0) {
10705            // We need *something*.  Take time time stamp of the file.
10706            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
10707        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
10708            if (scanFileTime != pkgSetting.timeStamp) {
10709                // A package on the system image has changed; consider this
10710                // to be an update.
10711                pkgSetting.lastUpdateTime = scanFileTime;
10712            }
10713        }
10714        pkgSetting.setTimeStamp(scanFileTime);
10715
10716        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10717            if (nonMutatedPs != null) {
10718                synchronized (mPackages) {
10719                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
10720                }
10721            }
10722        } else {
10723            final int userId = user == null ? 0 : user.getIdentifier();
10724            // Modify state for the given package setting
10725            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
10726                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
10727            if (pkgSetting.getInstantApp(userId)) {
10728                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
10729            }
10730        }
10731        return pkg;
10732    }
10733
10734    /**
10735     * Applies policy to the parsed package based upon the given policy flags.
10736     * Ensures the package is in a good state.
10737     * <p>
10738     * Implementation detail: This method must NOT have any side effect. It would
10739     * ideally be static, but, it requires locks to read system state.
10740     */
10741    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
10742        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
10743            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
10744            if (pkg.applicationInfo.isDirectBootAware()) {
10745                // we're direct boot aware; set for all components
10746                for (PackageParser.Service s : pkg.services) {
10747                    s.info.encryptionAware = s.info.directBootAware = true;
10748                }
10749                for (PackageParser.Provider p : pkg.providers) {
10750                    p.info.encryptionAware = p.info.directBootAware = true;
10751                }
10752                for (PackageParser.Activity a : pkg.activities) {
10753                    a.info.encryptionAware = a.info.directBootAware = true;
10754                }
10755                for (PackageParser.Activity r : pkg.receivers) {
10756                    r.info.encryptionAware = r.info.directBootAware = true;
10757                }
10758            }
10759        } else {
10760            // Only allow system apps to be flagged as core apps.
10761            pkg.coreApp = false;
10762            // clear flags not applicable to regular apps
10763            pkg.applicationInfo.privateFlags &=
10764                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
10765            pkg.applicationInfo.privateFlags &=
10766                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
10767        }
10768        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
10769
10770        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
10771            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
10772        }
10773
10774        if (!isSystemApp(pkg)) {
10775            // Only system apps can use these features.
10776            pkg.mOriginalPackages = null;
10777            pkg.mRealPackage = null;
10778            pkg.mAdoptPermissions = null;
10779        }
10780    }
10781
10782    /**
10783     * Asserts the parsed package is valid according to the given policy. If the
10784     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
10785     * <p>
10786     * Implementation detail: This method must NOT have any side effects. It would
10787     * ideally be static, but, it requires locks to read system state.
10788     *
10789     * @throws PackageManagerException If the package fails any of the validation checks
10790     */
10791    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
10792            throws PackageManagerException {
10793        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
10794            assertCodePolicy(pkg);
10795        }
10796
10797        if (pkg.applicationInfo.getCodePath() == null ||
10798                pkg.applicationInfo.getResourcePath() == null) {
10799            // Bail out. The resource and code paths haven't been set.
10800            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10801                    "Code and resource paths haven't been set correctly");
10802        }
10803
10804        // Make sure we're not adding any bogus keyset info
10805        KeySetManagerService ksms = mSettings.mKeySetManagerService;
10806        ksms.assertScannedPackageValid(pkg);
10807
10808        synchronized (mPackages) {
10809            // The special "android" package can only be defined once
10810            if (pkg.packageName.equals("android")) {
10811                if (mAndroidApplication != null) {
10812                    Slog.w(TAG, "*************************************************");
10813                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
10814                    Slog.w(TAG, " codePath=" + pkg.codePath);
10815                    Slog.w(TAG, "*************************************************");
10816                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10817                            "Core android package being redefined.  Skipping.");
10818                }
10819            }
10820
10821            // A package name must be unique; don't allow duplicates
10822            if (mPackages.containsKey(pkg.packageName)) {
10823                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10824                        "Application package " + pkg.packageName
10825                        + " already installed.  Skipping duplicate.");
10826            }
10827
10828            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10829                // Static libs have a synthetic package name containing the version
10830                // but we still want the base name to be unique.
10831                if (mPackages.containsKey(pkg.manifestPackageName)) {
10832                    throw new PackageManagerException(
10833                            "Duplicate static shared lib provider package");
10834                }
10835
10836                // Static shared libraries should have at least O target SDK
10837                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
10838                    throw new PackageManagerException(
10839                            "Packages declaring static-shared libs must target O SDK or higher");
10840                }
10841
10842                // Package declaring static a shared lib cannot be instant apps
10843                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10844                    throw new PackageManagerException(
10845                            "Packages declaring static-shared libs cannot be instant apps");
10846                }
10847
10848                // Package declaring static a shared lib cannot be renamed since the package
10849                // name is synthetic and apps can't code around package manager internals.
10850                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
10851                    throw new PackageManagerException(
10852                            "Packages declaring static-shared libs cannot be renamed");
10853                }
10854
10855                // Package declaring static a shared lib cannot declare child packages
10856                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
10857                    throw new PackageManagerException(
10858                            "Packages declaring static-shared libs cannot have child packages");
10859                }
10860
10861                // Package declaring static a shared lib cannot declare dynamic libs
10862                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
10863                    throw new PackageManagerException(
10864                            "Packages declaring static-shared libs cannot declare dynamic libs");
10865                }
10866
10867                // Package declaring static a shared lib cannot declare shared users
10868                if (pkg.mSharedUserId != null) {
10869                    throw new PackageManagerException(
10870                            "Packages declaring static-shared libs cannot declare shared users");
10871                }
10872
10873                // Static shared libs cannot declare activities
10874                if (!pkg.activities.isEmpty()) {
10875                    throw new PackageManagerException(
10876                            "Static shared libs cannot declare activities");
10877                }
10878
10879                // Static shared libs cannot declare services
10880                if (!pkg.services.isEmpty()) {
10881                    throw new PackageManagerException(
10882                            "Static shared libs cannot declare services");
10883                }
10884
10885                // Static shared libs cannot declare providers
10886                if (!pkg.providers.isEmpty()) {
10887                    throw new PackageManagerException(
10888                            "Static shared libs cannot declare content providers");
10889                }
10890
10891                // Static shared libs cannot declare receivers
10892                if (!pkg.receivers.isEmpty()) {
10893                    throw new PackageManagerException(
10894                            "Static shared libs cannot declare broadcast receivers");
10895                }
10896
10897                // Static shared libs cannot declare permission groups
10898                if (!pkg.permissionGroups.isEmpty()) {
10899                    throw new PackageManagerException(
10900                            "Static shared libs cannot declare permission groups");
10901                }
10902
10903                // Static shared libs cannot declare permissions
10904                if (!pkg.permissions.isEmpty()) {
10905                    throw new PackageManagerException(
10906                            "Static shared libs cannot declare permissions");
10907                }
10908
10909                // Static shared libs cannot declare protected broadcasts
10910                if (pkg.protectedBroadcasts != null) {
10911                    throw new PackageManagerException(
10912                            "Static shared libs cannot declare protected broadcasts");
10913                }
10914
10915                // Static shared libs cannot be overlay targets
10916                if (pkg.mOverlayTarget != null) {
10917                    throw new PackageManagerException(
10918                            "Static shared libs cannot be overlay targets");
10919                }
10920
10921                // The version codes must be ordered as lib versions
10922                int minVersionCode = Integer.MIN_VALUE;
10923                int maxVersionCode = Integer.MAX_VALUE;
10924
10925                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10926                        pkg.staticSharedLibName);
10927                if (versionedLib != null) {
10928                    final int versionCount = versionedLib.size();
10929                    for (int i = 0; i < versionCount; i++) {
10930                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
10931                        final int libVersionCode = libInfo.getDeclaringPackage()
10932                                .getVersionCode();
10933                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
10934                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
10935                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
10936                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
10937                        } else {
10938                            minVersionCode = maxVersionCode = libVersionCode;
10939                            break;
10940                        }
10941                    }
10942                }
10943                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
10944                    throw new PackageManagerException("Static shared"
10945                            + " lib version codes must be ordered as lib versions");
10946                }
10947            }
10948
10949            // Only privileged apps and updated privileged apps can add child packages.
10950            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
10951                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
10952                    throw new PackageManagerException("Only privileged apps can add child "
10953                            + "packages. Ignoring package " + pkg.packageName);
10954                }
10955                final int childCount = pkg.childPackages.size();
10956                for (int i = 0; i < childCount; i++) {
10957                    PackageParser.Package childPkg = pkg.childPackages.get(i);
10958                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
10959                            childPkg.packageName)) {
10960                        throw new PackageManagerException("Can't override child of "
10961                                + "another disabled app. Ignoring package " + pkg.packageName);
10962                    }
10963                }
10964            }
10965
10966            // If we're only installing presumed-existing packages, require that the
10967            // scanned APK is both already known and at the path previously established
10968            // for it.  Previously unknown packages we pick up normally, but if we have an
10969            // a priori expectation about this package's install presence, enforce it.
10970            // With a singular exception for new system packages. When an OTA contains
10971            // a new system package, we allow the codepath to change from a system location
10972            // to the user-installed location. If we don't allow this change, any newer,
10973            // user-installed version of the application will be ignored.
10974            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
10975                if (mExpectingBetter.containsKey(pkg.packageName)) {
10976                    logCriticalInfo(Log.WARN,
10977                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
10978                } else {
10979                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
10980                    if (known != null) {
10981                        if (DEBUG_PACKAGE_SCANNING) {
10982                            Log.d(TAG, "Examining " + pkg.codePath
10983                                    + " and requiring known paths " + known.codePathString
10984                                    + " & " + known.resourcePathString);
10985                        }
10986                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
10987                                || !pkg.applicationInfo.getResourcePath().equals(
10988                                        known.resourcePathString)) {
10989                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
10990                                    "Application package " + pkg.packageName
10991                                    + " found at " + pkg.applicationInfo.getCodePath()
10992                                    + " but expected at " + known.codePathString
10993                                    + "; ignoring.");
10994                        }
10995                    }
10996                }
10997            }
10998
10999            // Verify that this new package doesn't have any content providers
11000            // that conflict with existing packages.  Only do this if the
11001            // package isn't already installed, since we don't want to break
11002            // things that are installed.
11003            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
11004                final int N = pkg.providers.size();
11005                int i;
11006                for (i=0; i<N; i++) {
11007                    PackageParser.Provider p = pkg.providers.get(i);
11008                    if (p.info.authority != null) {
11009                        String names[] = p.info.authority.split(";");
11010                        for (int j = 0; j < names.length; j++) {
11011                            if (mProvidersByAuthority.containsKey(names[j])) {
11012                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11013                                final String otherPackageName =
11014                                        ((other != null && other.getComponentName() != null) ?
11015                                                other.getComponentName().getPackageName() : "?");
11016                                throw new PackageManagerException(
11017                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
11018                                        "Can't install because provider name " + names[j]
11019                                                + " (in package " + pkg.applicationInfo.packageName
11020                                                + ") is already used by " + otherPackageName);
11021                            }
11022                        }
11023                    }
11024                }
11025            }
11026        }
11027    }
11028
11029    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
11030            int type, String declaringPackageName, int declaringVersionCode) {
11031        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11032        if (versionedLib == null) {
11033            versionedLib = new SparseArray<>();
11034            mSharedLibraries.put(name, versionedLib);
11035            if (type == SharedLibraryInfo.TYPE_STATIC) {
11036                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
11037            }
11038        } else if (versionedLib.indexOfKey(version) >= 0) {
11039            return false;
11040        }
11041        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
11042                version, type, declaringPackageName, declaringVersionCode);
11043        versionedLib.put(version, libEntry);
11044        return true;
11045    }
11046
11047    private boolean removeSharedLibraryLPw(String name, int version) {
11048        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11049        if (versionedLib == null) {
11050            return false;
11051        }
11052        final int libIdx = versionedLib.indexOfKey(version);
11053        if (libIdx < 0) {
11054            return false;
11055        }
11056        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
11057        versionedLib.remove(version);
11058        if (versionedLib.size() <= 0) {
11059            mSharedLibraries.remove(name);
11060            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
11061                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
11062                        .getPackageName());
11063            }
11064        }
11065        return true;
11066    }
11067
11068    /**
11069     * Adds a scanned package to the system. When this method is finished, the package will
11070     * be available for query, resolution, etc...
11071     */
11072    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
11073            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
11074        final String pkgName = pkg.packageName;
11075        if (mCustomResolverComponentName != null &&
11076                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
11077            setUpCustomResolverActivity(pkg);
11078        }
11079
11080        if (pkg.packageName.equals("android")) {
11081            synchronized (mPackages) {
11082                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
11083                    // Set up information for our fall-back user intent resolution activity.
11084                    mPlatformPackage = pkg;
11085                    pkg.mVersionCode = mSdkVersion;
11086                    mAndroidApplication = pkg.applicationInfo;
11087                    if (!mResolverReplaced) {
11088                        mResolveActivity.applicationInfo = mAndroidApplication;
11089                        mResolveActivity.name = ResolverActivity.class.getName();
11090                        mResolveActivity.packageName = mAndroidApplication.packageName;
11091                        mResolveActivity.processName = "system:ui";
11092                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11093                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
11094                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
11095                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
11096                        mResolveActivity.exported = true;
11097                        mResolveActivity.enabled = true;
11098                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
11099                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
11100                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
11101                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
11102                                | ActivityInfo.CONFIG_ORIENTATION
11103                                | ActivityInfo.CONFIG_KEYBOARD
11104                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
11105                        mResolveInfo.activityInfo = mResolveActivity;
11106                        mResolveInfo.priority = 0;
11107                        mResolveInfo.preferredOrder = 0;
11108                        mResolveInfo.match = 0;
11109                        mResolveComponentName = new ComponentName(
11110                                mAndroidApplication.packageName, mResolveActivity.name);
11111                    }
11112                }
11113            }
11114        }
11115
11116        ArrayList<PackageParser.Package> clientLibPkgs = null;
11117        // writer
11118        synchronized (mPackages) {
11119            boolean hasStaticSharedLibs = false;
11120
11121            // Any app can add new static shared libraries
11122            if (pkg.staticSharedLibName != null) {
11123                // Static shared libs don't allow renaming as they have synthetic package
11124                // names to allow install of multiple versions, so use name from manifest.
11125                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
11126                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
11127                        pkg.manifestPackageName, pkg.mVersionCode)) {
11128                    hasStaticSharedLibs = true;
11129                } else {
11130                    Slog.w(TAG, "Package " + pkg.packageName + " library "
11131                                + pkg.staticSharedLibName + " already exists; skipping");
11132                }
11133                // Static shared libs cannot be updated once installed since they
11134                // use synthetic package name which includes the version code, so
11135                // not need to update other packages's shared lib dependencies.
11136            }
11137
11138            if (!hasStaticSharedLibs
11139                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11140                // Only system apps can add new dynamic shared libraries.
11141                if (pkg.libraryNames != null) {
11142                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
11143                        String name = pkg.libraryNames.get(i);
11144                        boolean allowed = false;
11145                        if (pkg.isUpdatedSystemApp()) {
11146                            // New library entries can only be added through the
11147                            // system image.  This is important to get rid of a lot
11148                            // of nasty edge cases: for example if we allowed a non-
11149                            // system update of the app to add a library, then uninstalling
11150                            // the update would make the library go away, and assumptions
11151                            // we made such as through app install filtering would now
11152                            // have allowed apps on the device which aren't compatible
11153                            // with it.  Better to just have the restriction here, be
11154                            // conservative, and create many fewer cases that can negatively
11155                            // impact the user experience.
11156                            final PackageSetting sysPs = mSettings
11157                                    .getDisabledSystemPkgLPr(pkg.packageName);
11158                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
11159                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
11160                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
11161                                        allowed = true;
11162                                        break;
11163                                    }
11164                                }
11165                            }
11166                        } else {
11167                            allowed = true;
11168                        }
11169                        if (allowed) {
11170                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
11171                                    SharedLibraryInfo.VERSION_UNDEFINED,
11172                                    SharedLibraryInfo.TYPE_DYNAMIC,
11173                                    pkg.packageName, pkg.mVersionCode)) {
11174                                Slog.w(TAG, "Package " + pkg.packageName + " library "
11175                                        + name + " already exists; skipping");
11176                            }
11177                        } else {
11178                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
11179                                    + name + " that is not declared on system image; skipping");
11180                        }
11181                    }
11182
11183                    if ((scanFlags & SCAN_BOOTING) == 0) {
11184                        // If we are not booting, we need to update any applications
11185                        // that are clients of our shared library.  If we are booting,
11186                        // this will all be done once the scan is complete.
11187                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
11188                    }
11189                }
11190            }
11191        }
11192
11193        if ((scanFlags & SCAN_BOOTING) != 0) {
11194            // No apps can run during boot scan, so they don't need to be frozen
11195        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
11196            // Caller asked to not kill app, so it's probably not frozen
11197        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
11198            // Caller asked us to ignore frozen check for some reason; they
11199            // probably didn't know the package name
11200        } else {
11201            // We're doing major surgery on this package, so it better be frozen
11202            // right now to keep it from launching
11203            checkPackageFrozen(pkgName);
11204        }
11205
11206        // Also need to kill any apps that are dependent on the library.
11207        if (clientLibPkgs != null) {
11208            for (int i=0; i<clientLibPkgs.size(); i++) {
11209                PackageParser.Package clientPkg = clientLibPkgs.get(i);
11210                killApplication(clientPkg.applicationInfo.packageName,
11211                        clientPkg.applicationInfo.uid, "update lib");
11212            }
11213        }
11214
11215        // writer
11216        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
11217
11218        synchronized (mPackages) {
11219            // We don't expect installation to fail beyond this point
11220
11221            // Add the new setting to mSettings
11222            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
11223            // Add the new setting to mPackages
11224            mPackages.put(pkg.applicationInfo.packageName, pkg);
11225            // Make sure we don't accidentally delete its data.
11226            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
11227            while (iter.hasNext()) {
11228                PackageCleanItem item = iter.next();
11229                if (pkgName.equals(item.packageName)) {
11230                    iter.remove();
11231                }
11232            }
11233
11234            // Add the package's KeySets to the global KeySetManagerService
11235            KeySetManagerService ksms = mSettings.mKeySetManagerService;
11236            ksms.addScannedPackageLPw(pkg);
11237
11238            int N = pkg.providers.size();
11239            StringBuilder r = null;
11240            int i;
11241            for (i=0; i<N; i++) {
11242                PackageParser.Provider p = pkg.providers.get(i);
11243                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11244                        p.info.processName);
11245                mProviders.addProvider(p);
11246                p.syncable = p.info.isSyncable;
11247                if (p.info.authority != null) {
11248                    String names[] = p.info.authority.split(";");
11249                    p.info.authority = null;
11250                    for (int j = 0; j < names.length; j++) {
11251                        if (j == 1 && p.syncable) {
11252                            // We only want the first authority for a provider to possibly be
11253                            // syncable, so if we already added this provider using a different
11254                            // authority clear the syncable flag. We copy the provider before
11255                            // changing it because the mProviders object contains a reference
11256                            // to a provider that we don't want to change.
11257                            // Only do this for the second authority since the resulting provider
11258                            // object can be the same for all future authorities for this provider.
11259                            p = new PackageParser.Provider(p);
11260                            p.syncable = false;
11261                        }
11262                        if (!mProvidersByAuthority.containsKey(names[j])) {
11263                            mProvidersByAuthority.put(names[j], p);
11264                            if (p.info.authority == null) {
11265                                p.info.authority = names[j];
11266                            } else {
11267                                p.info.authority = p.info.authority + ";" + names[j];
11268                            }
11269                            if (DEBUG_PACKAGE_SCANNING) {
11270                                if (chatty)
11271                                    Log.d(TAG, "Registered content provider: " + names[j]
11272                                            + ", className = " + p.info.name + ", isSyncable = "
11273                                            + p.info.isSyncable);
11274                            }
11275                        } else {
11276                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11277                            Slog.w(TAG, "Skipping provider name " + names[j] +
11278                                    " (in package " + pkg.applicationInfo.packageName +
11279                                    "): name already used by "
11280                                    + ((other != null && other.getComponentName() != null)
11281                                            ? other.getComponentName().getPackageName() : "?"));
11282                        }
11283                    }
11284                }
11285                if (chatty) {
11286                    if (r == null) {
11287                        r = new StringBuilder(256);
11288                    } else {
11289                        r.append(' ');
11290                    }
11291                    r.append(p.info.name);
11292                }
11293            }
11294            if (r != null) {
11295                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
11296            }
11297
11298            N = pkg.services.size();
11299            r = null;
11300            for (i=0; i<N; i++) {
11301                PackageParser.Service s = pkg.services.get(i);
11302                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11303                        s.info.processName);
11304                mServices.addService(s);
11305                if (chatty) {
11306                    if (r == null) {
11307                        r = new StringBuilder(256);
11308                    } else {
11309                        r.append(' ');
11310                    }
11311                    r.append(s.info.name);
11312                }
11313            }
11314            if (r != null) {
11315                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
11316            }
11317
11318            N = pkg.receivers.size();
11319            r = null;
11320            for (i=0; i<N; i++) {
11321                PackageParser.Activity a = pkg.receivers.get(i);
11322                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11323                        a.info.processName);
11324                mReceivers.addActivity(a, "receiver");
11325                if (chatty) {
11326                    if (r == null) {
11327                        r = new StringBuilder(256);
11328                    } else {
11329                        r.append(' ');
11330                    }
11331                    r.append(a.info.name);
11332                }
11333            }
11334            if (r != null) {
11335                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11336            }
11337
11338            N = pkg.activities.size();
11339            r = null;
11340            for (i=0; i<N; i++) {
11341                PackageParser.Activity a = pkg.activities.get(i);
11342                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11343                        a.info.processName);
11344                mActivities.addActivity(a, "activity");
11345                if (chatty) {
11346                    if (r == null) {
11347                        r = new StringBuilder(256);
11348                    } else {
11349                        r.append(' ');
11350                    }
11351                    r.append(a.info.name);
11352                }
11353            }
11354            if (r != null) {
11355                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11356            }
11357
11358            N = pkg.permissionGroups.size();
11359            r = null;
11360            for (i=0; i<N; i++) {
11361                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
11362                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
11363                final String curPackageName = cur == null ? null : cur.info.packageName;
11364                // Dont allow ephemeral apps to define new permission groups.
11365                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11366                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11367                            + pg.info.packageName
11368                            + " ignored: instant apps cannot define new permission groups.");
11369                    continue;
11370                }
11371                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
11372                if (cur == null || isPackageUpdate) {
11373                    mPermissionGroups.put(pg.info.name, pg);
11374                    if (chatty) {
11375                        if (r == null) {
11376                            r = new StringBuilder(256);
11377                        } else {
11378                            r.append(' ');
11379                        }
11380                        if (isPackageUpdate) {
11381                            r.append("UPD:");
11382                        }
11383                        r.append(pg.info.name);
11384                    }
11385                } else {
11386                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11387                            + pg.info.packageName + " ignored: original from "
11388                            + cur.info.packageName);
11389                    if (chatty) {
11390                        if (r == null) {
11391                            r = new StringBuilder(256);
11392                        } else {
11393                            r.append(' ');
11394                        }
11395                        r.append("DUP:");
11396                        r.append(pg.info.name);
11397                    }
11398                }
11399            }
11400            if (r != null) {
11401                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
11402            }
11403
11404            N = pkg.permissions.size();
11405            r = null;
11406            for (i=0; i<N; i++) {
11407                PackageParser.Permission p = pkg.permissions.get(i);
11408
11409                // Dont allow ephemeral apps to define new permissions.
11410                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11411                    Slog.w(TAG, "Permission " + p.info.name + " from package "
11412                            + p.info.packageName
11413                            + " ignored: instant apps cannot define new permissions.");
11414                    continue;
11415                }
11416
11417                // Assume by default that we did not install this permission into the system.
11418                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
11419
11420                // Now that permission groups have a special meaning, we ignore permission
11421                // groups for legacy apps to prevent unexpected behavior. In particular,
11422                // permissions for one app being granted to someone just because they happen
11423                // to be in a group defined by another app (before this had no implications).
11424                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
11425                    p.group = mPermissionGroups.get(p.info.group);
11426                    // Warn for a permission in an unknown group.
11427                    if (DEBUG_PERMISSIONS && p.info.group != null && p.group == null) {
11428                        Slog.i(TAG, "Permission " + p.info.name + " from package "
11429                                + p.info.packageName + " in an unknown group " + p.info.group);
11430                    }
11431                }
11432
11433                ArrayMap<String, BasePermission> permissionMap =
11434                        p.tree ? mSettings.mPermissionTrees
11435                                : mSettings.mPermissions;
11436                BasePermission bp = permissionMap.get(p.info.name);
11437
11438                // Allow system apps to redefine non-system permissions
11439                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
11440                    final boolean currentOwnerIsSystem = (bp.perm != null
11441                            && isSystemApp(bp.perm.owner));
11442                    if (isSystemApp(p.owner)) {
11443                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
11444                            // It's a built-in permission and no owner, take ownership now
11445                            bp.packageSetting = pkgSetting;
11446                            bp.perm = p;
11447                            bp.uid = pkg.applicationInfo.uid;
11448                            bp.sourcePackage = p.info.packageName;
11449                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11450                        } else if (!currentOwnerIsSystem) {
11451                            String msg = "New decl " + p.owner + " of permission  "
11452                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
11453                            reportSettingsProblem(Log.WARN, msg);
11454                            bp = null;
11455                        }
11456                    }
11457                }
11458
11459                if (bp == null) {
11460                    bp = new BasePermission(p.info.name, p.info.packageName,
11461                            BasePermission.TYPE_NORMAL);
11462                    permissionMap.put(p.info.name, bp);
11463                }
11464
11465                if (bp.perm == null) {
11466                    if (bp.sourcePackage == null
11467                            || bp.sourcePackage.equals(p.info.packageName)) {
11468                        BasePermission tree = findPermissionTreeLP(p.info.name);
11469                        if (tree == null
11470                                || tree.sourcePackage.equals(p.info.packageName)) {
11471                            bp.packageSetting = pkgSetting;
11472                            bp.perm = p;
11473                            bp.uid = pkg.applicationInfo.uid;
11474                            bp.sourcePackage = p.info.packageName;
11475                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11476                            if (chatty) {
11477                                if (r == null) {
11478                                    r = new StringBuilder(256);
11479                                } else {
11480                                    r.append(' ');
11481                                }
11482                                r.append(p.info.name);
11483                            }
11484                        } else {
11485                            Slog.w(TAG, "Permission " + p.info.name + " from package "
11486                                    + p.info.packageName + " ignored: base tree "
11487                                    + tree.name + " is from package "
11488                                    + tree.sourcePackage);
11489                        }
11490                    } else {
11491                        Slog.w(TAG, "Permission " + p.info.name + " from package "
11492                                + p.info.packageName + " ignored: original from "
11493                                + bp.sourcePackage);
11494                    }
11495                } else if (chatty) {
11496                    if (r == null) {
11497                        r = new StringBuilder(256);
11498                    } else {
11499                        r.append(' ');
11500                    }
11501                    r.append("DUP:");
11502                    r.append(p.info.name);
11503                }
11504                if (bp.perm == p) {
11505                    bp.protectionLevel = p.info.protectionLevel;
11506                }
11507            }
11508
11509            if (r != null) {
11510                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
11511            }
11512
11513            N = pkg.instrumentation.size();
11514            r = null;
11515            for (i=0; i<N; i++) {
11516                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11517                a.info.packageName = pkg.applicationInfo.packageName;
11518                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11519                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11520                a.info.splitNames = pkg.splitNames;
11521                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11522                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11523                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11524                a.info.dataDir = pkg.applicationInfo.dataDir;
11525                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11526                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11527                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11528                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11529                mInstrumentation.put(a.getComponentName(), a);
11530                if (chatty) {
11531                    if (r == null) {
11532                        r = new StringBuilder(256);
11533                    } else {
11534                        r.append(' ');
11535                    }
11536                    r.append(a.info.name);
11537                }
11538            }
11539            if (r != null) {
11540                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
11541            }
11542
11543            if (pkg.protectedBroadcasts != null) {
11544                N = pkg.protectedBroadcasts.size();
11545                for (i=0; i<N; i++) {
11546                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11547                }
11548            }
11549        }
11550
11551        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11552    }
11553
11554    /**
11555     * Derive the ABI of a non-system package located at {@code scanFile}. This information
11556     * is derived purely on the basis of the contents of {@code scanFile} and
11557     * {@code cpuAbiOverride}.
11558     *
11559     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
11560     */
11561    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
11562                                 String cpuAbiOverride, boolean extractLibs,
11563                                 File appLib32InstallDir)
11564            throws PackageManagerException {
11565        // Give ourselves some initial paths; we'll come back for another
11566        // pass once we've determined ABI below.
11567        setNativeLibraryPaths(pkg, appLib32InstallDir);
11568
11569        // We would never need to extract libs for forward-locked and external packages,
11570        // since the container service will do it for us. We shouldn't attempt to
11571        // extract libs from system app when it was not updated.
11572        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
11573                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
11574            extractLibs = false;
11575        }
11576
11577        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
11578        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
11579
11580        NativeLibraryHelper.Handle handle = null;
11581        try {
11582            handle = NativeLibraryHelper.Handle.create(pkg);
11583            // TODO(multiArch): This can be null for apps that didn't go through the
11584            // usual installation process. We can calculate it again, like we
11585            // do during install time.
11586            //
11587            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
11588            // unnecessary.
11589            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
11590
11591            // Null out the abis so that they can be recalculated.
11592            pkg.applicationInfo.primaryCpuAbi = null;
11593            pkg.applicationInfo.secondaryCpuAbi = null;
11594            if (isMultiArch(pkg.applicationInfo)) {
11595                // Warn if we've set an abiOverride for multi-lib packages..
11596                // By definition, we need to copy both 32 and 64 bit libraries for
11597                // such packages.
11598                if (pkg.cpuAbiOverride != null
11599                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
11600                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
11601                }
11602
11603                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
11604                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
11605                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
11606                    if (extractLibs) {
11607                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11608                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11609                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
11610                                useIsaSpecificSubdirs);
11611                    } else {
11612                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11613                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
11614                    }
11615                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11616                }
11617
11618                // Shared library native code should be in the APK zip aligned
11619                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
11620                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11621                            "Shared library native lib extraction not supported");
11622                }
11623
11624                maybeThrowExceptionForMultiArchCopy(
11625                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
11626
11627                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
11628                    if (extractLibs) {
11629                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11630                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11631                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
11632                                useIsaSpecificSubdirs);
11633                    } else {
11634                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11635                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
11636                    }
11637                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11638                }
11639
11640                maybeThrowExceptionForMultiArchCopy(
11641                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
11642
11643                if (abi64 >= 0) {
11644                    // Shared library native libs should be in the APK zip aligned
11645                    if (extractLibs && pkg.isLibrary()) {
11646                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11647                                "Shared library native lib extraction not supported");
11648                    }
11649                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
11650                }
11651
11652                if (abi32 >= 0) {
11653                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
11654                    if (abi64 >= 0) {
11655                        if (pkg.use32bitAbi) {
11656                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11657                            pkg.applicationInfo.primaryCpuAbi = abi;
11658                        } else {
11659                            pkg.applicationInfo.secondaryCpuAbi = abi;
11660                        }
11661                    } else {
11662                        pkg.applicationInfo.primaryCpuAbi = abi;
11663                    }
11664                }
11665            } else {
11666                String[] abiList = (cpuAbiOverride != null) ?
11667                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
11668
11669                // Enable gross and lame hacks for apps that are built with old
11670                // SDK tools. We must scan their APKs for renderscript bitcode and
11671                // not launch them if it's present. Don't bother checking on devices
11672                // that don't have 64 bit support.
11673                boolean needsRenderScriptOverride = false;
11674                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
11675                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
11676                    abiList = Build.SUPPORTED_32_BIT_ABIS;
11677                    needsRenderScriptOverride = true;
11678                }
11679
11680                final int copyRet;
11681                if (extractLibs) {
11682                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11683                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11684                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
11685                } else {
11686                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11687                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
11688                }
11689                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11690
11691                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
11692                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11693                            "Error unpackaging native libs for app, errorCode=" + copyRet);
11694                }
11695
11696                if (copyRet >= 0) {
11697                    // Shared libraries that have native libs must be multi-architecture
11698                    if (pkg.isLibrary()) {
11699                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11700                                "Shared library with native libs must be multiarch");
11701                    }
11702                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
11703                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
11704                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
11705                } else if (needsRenderScriptOverride) {
11706                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
11707                }
11708            }
11709        } catch (IOException ioe) {
11710            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
11711        } finally {
11712            IoUtils.closeQuietly(handle);
11713        }
11714
11715        // Now that we've calculated the ABIs and determined if it's an internal app,
11716        // we will go ahead and populate the nativeLibraryPath.
11717        setNativeLibraryPaths(pkg, appLib32InstallDir);
11718    }
11719
11720    /**
11721     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
11722     * i.e, so that all packages can be run inside a single process if required.
11723     *
11724     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
11725     * this function will either try and make the ABI for all packages in {@code packagesForUser}
11726     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
11727     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
11728     * updating a package that belongs to a shared user.
11729     *
11730     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
11731     * adds unnecessary complexity.
11732     */
11733    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
11734            PackageParser.Package scannedPackage) {
11735        String requiredInstructionSet = null;
11736        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
11737            requiredInstructionSet = VMRuntime.getInstructionSet(
11738                     scannedPackage.applicationInfo.primaryCpuAbi);
11739        }
11740
11741        PackageSetting requirer = null;
11742        for (PackageSetting ps : packagesForUser) {
11743            // If packagesForUser contains scannedPackage, we skip it. This will happen
11744            // when scannedPackage is an update of an existing package. Without this check,
11745            // we will never be able to change the ABI of any package belonging to a shared
11746            // user, even if it's compatible with other packages.
11747            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11748                if (ps.primaryCpuAbiString == null) {
11749                    continue;
11750                }
11751
11752                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
11753                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
11754                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
11755                    // this but there's not much we can do.
11756                    String errorMessage = "Instruction set mismatch, "
11757                            + ((requirer == null) ? "[caller]" : requirer)
11758                            + " requires " + requiredInstructionSet + " whereas " + ps
11759                            + " requires " + instructionSet;
11760                    Slog.w(TAG, errorMessage);
11761                }
11762
11763                if (requiredInstructionSet == null) {
11764                    requiredInstructionSet = instructionSet;
11765                    requirer = ps;
11766                }
11767            }
11768        }
11769
11770        if (requiredInstructionSet != null) {
11771            String adjustedAbi;
11772            if (requirer != null) {
11773                // requirer != null implies that either scannedPackage was null or that scannedPackage
11774                // did not require an ABI, in which case we have to adjust scannedPackage to match
11775                // the ABI of the set (which is the same as requirer's ABI)
11776                adjustedAbi = requirer.primaryCpuAbiString;
11777                if (scannedPackage != null) {
11778                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
11779                }
11780            } else {
11781                // requirer == null implies that we're updating all ABIs in the set to
11782                // match scannedPackage.
11783                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
11784            }
11785
11786            for (PackageSetting ps : packagesForUser) {
11787                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11788                    if (ps.primaryCpuAbiString != null) {
11789                        continue;
11790                    }
11791
11792                    ps.primaryCpuAbiString = adjustedAbi;
11793                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
11794                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
11795                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
11796                        if (DEBUG_ABI_SELECTION) {
11797                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
11798                                    + " (requirer="
11799                                    + (requirer != null ? requirer.pkg : "null")
11800                                    + ", scannedPackage="
11801                                    + (scannedPackage != null ? scannedPackage : "null")
11802                                    + ")");
11803                        }
11804                        try {
11805                            mInstaller.rmdex(ps.codePathString,
11806                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
11807                        } catch (InstallerException ignored) {
11808                        }
11809                    }
11810                }
11811            }
11812        }
11813    }
11814
11815    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
11816        synchronized (mPackages) {
11817            mResolverReplaced = true;
11818            // Set up information for custom user intent resolution activity.
11819            mResolveActivity.applicationInfo = pkg.applicationInfo;
11820            mResolveActivity.name = mCustomResolverComponentName.getClassName();
11821            mResolveActivity.packageName = pkg.applicationInfo.packageName;
11822            mResolveActivity.processName = pkg.applicationInfo.packageName;
11823            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11824            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
11825                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11826            mResolveActivity.theme = 0;
11827            mResolveActivity.exported = true;
11828            mResolveActivity.enabled = true;
11829            mResolveInfo.activityInfo = mResolveActivity;
11830            mResolveInfo.priority = 0;
11831            mResolveInfo.preferredOrder = 0;
11832            mResolveInfo.match = 0;
11833            mResolveComponentName = mCustomResolverComponentName;
11834            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
11835                    mResolveComponentName);
11836        }
11837    }
11838
11839    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
11840        if (installerActivity == null) {
11841            if (DEBUG_EPHEMERAL) {
11842                Slog.d(TAG, "Clear ephemeral installer activity");
11843            }
11844            mInstantAppInstallerActivity = null;
11845            return;
11846        }
11847
11848        if (DEBUG_EPHEMERAL) {
11849            Slog.d(TAG, "Set ephemeral installer activity: "
11850                    + installerActivity.getComponentName());
11851        }
11852        // Set up information for ephemeral installer activity
11853        mInstantAppInstallerActivity = installerActivity;
11854        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
11855                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11856        mInstantAppInstallerActivity.exported = true;
11857        mInstantAppInstallerActivity.enabled = true;
11858        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
11859        mInstantAppInstallerInfo.priority = 0;
11860        mInstantAppInstallerInfo.preferredOrder = 1;
11861        mInstantAppInstallerInfo.isDefault = true;
11862        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
11863                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
11864    }
11865
11866    private static String calculateBundledApkRoot(final String codePathString) {
11867        final File codePath = new File(codePathString);
11868        final File codeRoot;
11869        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
11870            codeRoot = Environment.getRootDirectory();
11871        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
11872            codeRoot = Environment.getOemDirectory();
11873        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
11874            codeRoot = Environment.getVendorDirectory();
11875        } else {
11876            // Unrecognized code path; take its top real segment as the apk root:
11877            // e.g. /something/app/blah.apk => /something
11878            try {
11879                File f = codePath.getCanonicalFile();
11880                File parent = f.getParentFile();    // non-null because codePath is a file
11881                File tmp;
11882                while ((tmp = parent.getParentFile()) != null) {
11883                    f = parent;
11884                    parent = tmp;
11885                }
11886                codeRoot = f;
11887                Slog.w(TAG, "Unrecognized code path "
11888                        + codePath + " - using " + codeRoot);
11889            } catch (IOException e) {
11890                // Can't canonicalize the code path -- shenanigans?
11891                Slog.w(TAG, "Can't canonicalize code path " + codePath);
11892                return Environment.getRootDirectory().getPath();
11893            }
11894        }
11895        return codeRoot.getPath();
11896    }
11897
11898    /**
11899     * Derive and set the location of native libraries for the given package,
11900     * which varies depending on where and how the package was installed.
11901     */
11902    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
11903        final ApplicationInfo info = pkg.applicationInfo;
11904        final String codePath = pkg.codePath;
11905        final File codeFile = new File(codePath);
11906        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
11907        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
11908
11909        info.nativeLibraryRootDir = null;
11910        info.nativeLibraryRootRequiresIsa = false;
11911        info.nativeLibraryDir = null;
11912        info.secondaryNativeLibraryDir = null;
11913
11914        if (isApkFile(codeFile)) {
11915            // Monolithic install
11916            if (bundledApp) {
11917                // If "/system/lib64/apkname" exists, assume that is the per-package
11918                // native library directory to use; otherwise use "/system/lib/apkname".
11919                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
11920                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
11921                        getPrimaryInstructionSet(info));
11922
11923                // This is a bundled system app so choose the path based on the ABI.
11924                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
11925                // is just the default path.
11926                final String apkName = deriveCodePathName(codePath);
11927                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
11928                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
11929                        apkName).getAbsolutePath();
11930
11931                if (info.secondaryCpuAbi != null) {
11932                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
11933                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
11934                            secondaryLibDir, apkName).getAbsolutePath();
11935                }
11936            } else if (asecApp) {
11937                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
11938                        .getAbsolutePath();
11939            } else {
11940                final String apkName = deriveCodePathName(codePath);
11941                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
11942                        .getAbsolutePath();
11943            }
11944
11945            info.nativeLibraryRootRequiresIsa = false;
11946            info.nativeLibraryDir = info.nativeLibraryRootDir;
11947        } else {
11948            // Cluster install
11949            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
11950            info.nativeLibraryRootRequiresIsa = true;
11951
11952            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
11953                    getPrimaryInstructionSet(info)).getAbsolutePath();
11954
11955            if (info.secondaryCpuAbi != null) {
11956                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
11957                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
11958            }
11959        }
11960    }
11961
11962    /**
11963     * Calculate the abis and roots for a bundled app. These can uniquely
11964     * be determined from the contents of the system partition, i.e whether
11965     * it contains 64 or 32 bit shared libraries etc. We do not validate any
11966     * of this information, and instead assume that the system was built
11967     * sensibly.
11968     */
11969    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
11970                                           PackageSetting pkgSetting) {
11971        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
11972
11973        // If "/system/lib64/apkname" exists, assume that is the per-package
11974        // native library directory to use; otherwise use "/system/lib/apkname".
11975        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
11976        setBundledAppAbi(pkg, apkRoot, apkName);
11977        // pkgSetting might be null during rescan following uninstall of updates
11978        // to a bundled app, so accommodate that possibility.  The settings in
11979        // that case will be established later from the parsed package.
11980        //
11981        // If the settings aren't null, sync them up with what we've just derived.
11982        // note that apkRoot isn't stored in the package settings.
11983        if (pkgSetting != null) {
11984            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11985            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11986        }
11987    }
11988
11989    /**
11990     * Deduces the ABI of a bundled app and sets the relevant fields on the
11991     * parsed pkg object.
11992     *
11993     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
11994     *        under which system libraries are installed.
11995     * @param apkName the name of the installed package.
11996     */
11997    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
11998        final File codeFile = new File(pkg.codePath);
11999
12000        final boolean has64BitLibs;
12001        final boolean has32BitLibs;
12002        if (isApkFile(codeFile)) {
12003            // Monolithic install
12004            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
12005            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
12006        } else {
12007            // Cluster install
12008            final File rootDir = new File(codeFile, LIB_DIR_NAME);
12009            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
12010                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
12011                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
12012                has64BitLibs = (new File(rootDir, isa)).exists();
12013            } else {
12014                has64BitLibs = false;
12015            }
12016            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
12017                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
12018                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
12019                has32BitLibs = (new File(rootDir, isa)).exists();
12020            } else {
12021                has32BitLibs = false;
12022            }
12023        }
12024
12025        if (has64BitLibs && !has32BitLibs) {
12026            // The package has 64 bit libs, but not 32 bit libs. Its primary
12027            // ABI should be 64 bit. We can safely assume here that the bundled
12028            // native libraries correspond to the most preferred ABI in the list.
12029
12030            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12031            pkg.applicationInfo.secondaryCpuAbi = null;
12032        } else if (has32BitLibs && !has64BitLibs) {
12033            // The package has 32 bit libs but not 64 bit libs. Its primary
12034            // ABI should be 32 bit.
12035
12036            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12037            pkg.applicationInfo.secondaryCpuAbi = null;
12038        } else if (has32BitLibs && has64BitLibs) {
12039            // The application has both 64 and 32 bit bundled libraries. We check
12040            // here that the app declares multiArch support, and warn if it doesn't.
12041            //
12042            // We will be lenient here and record both ABIs. The primary will be the
12043            // ABI that's higher on the list, i.e, a device that's configured to prefer
12044            // 64 bit apps will see a 64 bit primary ABI,
12045
12046            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
12047                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
12048            }
12049
12050            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
12051                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12052                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12053            } else {
12054                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12055                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12056            }
12057        } else {
12058            pkg.applicationInfo.primaryCpuAbi = null;
12059            pkg.applicationInfo.secondaryCpuAbi = null;
12060        }
12061    }
12062
12063    private void killApplication(String pkgName, int appId, String reason) {
12064        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
12065    }
12066
12067    private void killApplication(String pkgName, int appId, int userId, String reason) {
12068        // Request the ActivityManager to kill the process(only for existing packages)
12069        // so that we do not end up in a confused state while the user is still using the older
12070        // version of the application while the new one gets installed.
12071        final long token = Binder.clearCallingIdentity();
12072        try {
12073            IActivityManager am = ActivityManager.getService();
12074            if (am != null) {
12075                try {
12076                    am.killApplication(pkgName, appId, userId, reason);
12077                } catch (RemoteException e) {
12078                }
12079            }
12080        } finally {
12081            Binder.restoreCallingIdentity(token);
12082        }
12083    }
12084
12085    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
12086        // Remove the parent package setting
12087        PackageSetting ps = (PackageSetting) pkg.mExtras;
12088        if (ps != null) {
12089            removePackageLI(ps, chatty);
12090        }
12091        // Remove the child package setting
12092        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12093        for (int i = 0; i < childCount; i++) {
12094            PackageParser.Package childPkg = pkg.childPackages.get(i);
12095            ps = (PackageSetting) childPkg.mExtras;
12096            if (ps != null) {
12097                removePackageLI(ps, chatty);
12098            }
12099        }
12100    }
12101
12102    void removePackageLI(PackageSetting ps, boolean chatty) {
12103        if (DEBUG_INSTALL) {
12104            if (chatty)
12105                Log.d(TAG, "Removing package " + ps.name);
12106        }
12107
12108        // writer
12109        synchronized (mPackages) {
12110            mPackages.remove(ps.name);
12111            final PackageParser.Package pkg = ps.pkg;
12112            if (pkg != null) {
12113                cleanPackageDataStructuresLILPw(pkg, chatty);
12114            }
12115        }
12116    }
12117
12118    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
12119        if (DEBUG_INSTALL) {
12120            if (chatty)
12121                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
12122        }
12123
12124        // writer
12125        synchronized (mPackages) {
12126            // Remove the parent package
12127            mPackages.remove(pkg.applicationInfo.packageName);
12128            cleanPackageDataStructuresLILPw(pkg, chatty);
12129
12130            // Remove the child packages
12131            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12132            for (int i = 0; i < childCount; i++) {
12133                PackageParser.Package childPkg = pkg.childPackages.get(i);
12134                mPackages.remove(childPkg.applicationInfo.packageName);
12135                cleanPackageDataStructuresLILPw(childPkg, chatty);
12136            }
12137        }
12138    }
12139
12140    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
12141        int N = pkg.providers.size();
12142        StringBuilder r = null;
12143        int i;
12144        for (i=0; i<N; i++) {
12145            PackageParser.Provider p = pkg.providers.get(i);
12146            mProviders.removeProvider(p);
12147            if (p.info.authority == null) {
12148
12149                /* There was another ContentProvider with this authority when
12150                 * this app was installed so this authority is null,
12151                 * Ignore it as we don't have to unregister the provider.
12152                 */
12153                continue;
12154            }
12155            String names[] = p.info.authority.split(";");
12156            for (int j = 0; j < names.length; j++) {
12157                if (mProvidersByAuthority.get(names[j]) == p) {
12158                    mProvidersByAuthority.remove(names[j]);
12159                    if (DEBUG_REMOVE) {
12160                        if (chatty)
12161                            Log.d(TAG, "Unregistered content provider: " + names[j]
12162                                    + ", className = " + p.info.name + ", isSyncable = "
12163                                    + p.info.isSyncable);
12164                    }
12165                }
12166            }
12167            if (DEBUG_REMOVE && chatty) {
12168                if (r == null) {
12169                    r = new StringBuilder(256);
12170                } else {
12171                    r.append(' ');
12172                }
12173                r.append(p.info.name);
12174            }
12175        }
12176        if (r != null) {
12177            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
12178        }
12179
12180        N = pkg.services.size();
12181        r = null;
12182        for (i=0; i<N; i++) {
12183            PackageParser.Service s = pkg.services.get(i);
12184            mServices.removeService(s);
12185            if (chatty) {
12186                if (r == null) {
12187                    r = new StringBuilder(256);
12188                } else {
12189                    r.append(' ');
12190                }
12191                r.append(s.info.name);
12192            }
12193        }
12194        if (r != null) {
12195            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
12196        }
12197
12198        N = pkg.receivers.size();
12199        r = null;
12200        for (i=0; i<N; i++) {
12201            PackageParser.Activity a = pkg.receivers.get(i);
12202            mReceivers.removeActivity(a, "receiver");
12203            if (DEBUG_REMOVE && chatty) {
12204                if (r == null) {
12205                    r = new StringBuilder(256);
12206                } else {
12207                    r.append(' ');
12208                }
12209                r.append(a.info.name);
12210            }
12211        }
12212        if (r != null) {
12213            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
12214        }
12215
12216        N = pkg.activities.size();
12217        r = null;
12218        for (i=0; i<N; i++) {
12219            PackageParser.Activity a = pkg.activities.get(i);
12220            mActivities.removeActivity(a, "activity");
12221            if (DEBUG_REMOVE && chatty) {
12222                if (r == null) {
12223                    r = new StringBuilder(256);
12224                } else {
12225                    r.append(' ');
12226                }
12227                r.append(a.info.name);
12228            }
12229        }
12230        if (r != null) {
12231            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
12232        }
12233
12234        N = pkg.permissions.size();
12235        r = null;
12236        for (i=0; i<N; i++) {
12237            PackageParser.Permission p = pkg.permissions.get(i);
12238            BasePermission bp = mSettings.mPermissions.get(p.info.name);
12239            if (bp == null) {
12240                bp = mSettings.mPermissionTrees.get(p.info.name);
12241            }
12242            if (bp != null && bp.perm == p) {
12243                bp.perm = null;
12244                if (DEBUG_REMOVE && chatty) {
12245                    if (r == null) {
12246                        r = new StringBuilder(256);
12247                    } else {
12248                        r.append(' ');
12249                    }
12250                    r.append(p.info.name);
12251                }
12252            }
12253            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12254                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
12255                if (appOpPkgs != null) {
12256                    appOpPkgs.remove(pkg.packageName);
12257                }
12258            }
12259        }
12260        if (r != null) {
12261            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12262        }
12263
12264        N = pkg.requestedPermissions.size();
12265        r = null;
12266        for (i=0; i<N; i++) {
12267            String perm = pkg.requestedPermissions.get(i);
12268            BasePermission bp = mSettings.mPermissions.get(perm);
12269            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12270                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
12271                if (appOpPkgs != null) {
12272                    appOpPkgs.remove(pkg.packageName);
12273                    if (appOpPkgs.isEmpty()) {
12274                        mAppOpPermissionPackages.remove(perm);
12275                    }
12276                }
12277            }
12278        }
12279        if (r != null) {
12280            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12281        }
12282
12283        N = pkg.instrumentation.size();
12284        r = null;
12285        for (i=0; i<N; i++) {
12286            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
12287            mInstrumentation.remove(a.getComponentName());
12288            if (DEBUG_REMOVE && chatty) {
12289                if (r == null) {
12290                    r = new StringBuilder(256);
12291                } else {
12292                    r.append(' ');
12293                }
12294                r.append(a.info.name);
12295            }
12296        }
12297        if (r != null) {
12298            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
12299        }
12300
12301        r = null;
12302        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
12303            // Only system apps can hold shared libraries.
12304            if (pkg.libraryNames != null) {
12305                for (i = 0; i < pkg.libraryNames.size(); i++) {
12306                    String name = pkg.libraryNames.get(i);
12307                    if (removeSharedLibraryLPw(name, 0)) {
12308                        if (DEBUG_REMOVE && chatty) {
12309                            if (r == null) {
12310                                r = new StringBuilder(256);
12311                            } else {
12312                                r.append(' ');
12313                            }
12314                            r.append(name);
12315                        }
12316                    }
12317                }
12318            }
12319        }
12320
12321        r = null;
12322
12323        // Any package can hold static shared libraries.
12324        if (pkg.staticSharedLibName != null) {
12325            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
12326                if (DEBUG_REMOVE && chatty) {
12327                    if (r == null) {
12328                        r = new StringBuilder(256);
12329                    } else {
12330                        r.append(' ');
12331                    }
12332                    r.append(pkg.staticSharedLibName);
12333                }
12334            }
12335        }
12336
12337        if (r != null) {
12338            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
12339        }
12340    }
12341
12342    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
12343        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
12344            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
12345                return true;
12346            }
12347        }
12348        return false;
12349    }
12350
12351    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
12352    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
12353    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
12354
12355    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
12356        // Update the parent permissions
12357        updatePermissionsLPw(pkg.packageName, pkg, flags);
12358        // Update the child permissions
12359        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12360        for (int i = 0; i < childCount; i++) {
12361            PackageParser.Package childPkg = pkg.childPackages.get(i);
12362            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
12363        }
12364    }
12365
12366    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
12367            int flags) {
12368        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
12369        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
12370    }
12371
12372    private void updatePermissionsLPw(String changingPkg,
12373            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
12374        // Make sure there are no dangling permission trees.
12375        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
12376        while (it.hasNext()) {
12377            final BasePermission bp = it.next();
12378            if (bp.packageSetting == null) {
12379                // We may not yet have parsed the package, so just see if
12380                // we still know about its settings.
12381                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12382            }
12383            if (bp.packageSetting == null) {
12384                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
12385                        + " from package " + bp.sourcePackage);
12386                it.remove();
12387            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12388                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12389                    Slog.i(TAG, "Removing old permission tree: " + bp.name
12390                            + " from package " + bp.sourcePackage);
12391                    flags |= UPDATE_PERMISSIONS_ALL;
12392                    it.remove();
12393                }
12394            }
12395        }
12396
12397        // Make sure all dynamic permissions have been assigned to a package,
12398        // and make sure there are no dangling permissions.
12399        it = mSettings.mPermissions.values().iterator();
12400        while (it.hasNext()) {
12401            final BasePermission bp = it.next();
12402            if (bp.type == BasePermission.TYPE_DYNAMIC) {
12403                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
12404                        + bp.name + " pkg=" + bp.sourcePackage
12405                        + " info=" + bp.pendingInfo);
12406                if (bp.packageSetting == null && bp.pendingInfo != null) {
12407                    final BasePermission tree = findPermissionTreeLP(bp.name);
12408                    if (tree != null && tree.perm != null) {
12409                        bp.packageSetting = tree.packageSetting;
12410                        bp.perm = new PackageParser.Permission(tree.perm.owner,
12411                                new PermissionInfo(bp.pendingInfo));
12412                        bp.perm.info.packageName = tree.perm.info.packageName;
12413                        bp.perm.info.name = bp.name;
12414                        bp.uid = tree.uid;
12415                    }
12416                }
12417            }
12418            if (bp.packageSetting == null) {
12419                // We may not yet have parsed the package, so just see if
12420                // we still know about its settings.
12421                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12422            }
12423            if (bp.packageSetting == null) {
12424                Slog.w(TAG, "Removing dangling permission: " + bp.name
12425                        + " from package " + bp.sourcePackage);
12426                it.remove();
12427            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12428                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12429                    Slog.i(TAG, "Removing old permission: " + bp.name
12430                            + " from package " + bp.sourcePackage);
12431                    flags |= UPDATE_PERMISSIONS_ALL;
12432                    it.remove();
12433                }
12434            }
12435        }
12436
12437        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
12438        // Now update the permissions for all packages, in particular
12439        // replace the granted permissions of the system packages.
12440        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
12441            for (PackageParser.Package pkg : mPackages.values()) {
12442                if (pkg != pkgInfo) {
12443                    // Only replace for packages on requested volume
12444                    final String volumeUuid = getVolumeUuidForPackage(pkg);
12445                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
12446                            && Objects.equals(replaceVolumeUuid, volumeUuid);
12447                    grantPermissionsLPw(pkg, replace, changingPkg);
12448                }
12449            }
12450        }
12451
12452        if (pkgInfo != null) {
12453            // Only replace for packages on requested volume
12454            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
12455            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
12456                    && Objects.equals(replaceVolumeUuid, volumeUuid);
12457            grantPermissionsLPw(pkgInfo, replace, changingPkg);
12458        }
12459        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12460    }
12461
12462    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
12463            String packageOfInterest) {
12464        // IMPORTANT: There are two types of permissions: install and runtime.
12465        // Install time permissions are granted when the app is installed to
12466        // all device users and users added in the future. Runtime permissions
12467        // are granted at runtime explicitly to specific users. Normal and signature
12468        // protected permissions are install time permissions. Dangerous permissions
12469        // are install permissions if the app's target SDK is Lollipop MR1 or older,
12470        // otherwise they are runtime permissions. This function does not manage
12471        // runtime permissions except for the case an app targeting Lollipop MR1
12472        // being upgraded to target a newer SDK, in which case dangerous permissions
12473        // are transformed from install time to runtime ones.
12474
12475        final PackageSetting ps = (PackageSetting) pkg.mExtras;
12476        if (ps == null) {
12477            return;
12478        }
12479
12480        PermissionsState permissionsState = ps.getPermissionsState();
12481        PermissionsState origPermissions = permissionsState;
12482
12483        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
12484
12485        boolean runtimePermissionsRevoked = false;
12486        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
12487
12488        boolean changedInstallPermission = false;
12489
12490        if (replace) {
12491            ps.installPermissionsFixed = false;
12492            if (!ps.isSharedUser()) {
12493                origPermissions = new PermissionsState(permissionsState);
12494                permissionsState.reset();
12495            } else {
12496                // We need to know only about runtime permission changes since the
12497                // calling code always writes the install permissions state but
12498                // the runtime ones are written only if changed. The only cases of
12499                // changed runtime permissions here are promotion of an install to
12500                // runtime and revocation of a runtime from a shared user.
12501                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
12502                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
12503                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
12504                    runtimePermissionsRevoked = true;
12505                }
12506            }
12507        }
12508
12509        permissionsState.setGlobalGids(mGlobalGids);
12510
12511        final int N = pkg.requestedPermissions.size();
12512        for (int i=0; i<N; i++) {
12513            final String name = pkg.requestedPermissions.get(i);
12514            final BasePermission bp = mSettings.mPermissions.get(name);
12515            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
12516                    >= Build.VERSION_CODES.M;
12517
12518            if (DEBUG_INSTALL) {
12519                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
12520            }
12521
12522            if (bp == null || bp.packageSetting == null) {
12523                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
12524                    if (DEBUG_PERMISSIONS) {
12525                        Slog.i(TAG, "Unknown permission " + name
12526                                + " in package " + pkg.packageName);
12527                    }
12528                }
12529                continue;
12530            }
12531
12532
12533            // Limit ephemeral apps to ephemeral allowed permissions.
12534            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
12535                if (DEBUG_PERMISSIONS) {
12536                    Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
12537                            + pkg.packageName);
12538                }
12539                continue;
12540            }
12541
12542            if (bp.isRuntimeOnly() && !appSupportsRuntimePermissions) {
12543                if (DEBUG_PERMISSIONS) {
12544                    Log.i(TAG, "Denying runtime-only permission " + bp.name + " for package "
12545                            + pkg.packageName);
12546                }
12547                continue;
12548            }
12549
12550            final String perm = bp.name;
12551            boolean allowedSig = false;
12552            int grant = GRANT_DENIED;
12553
12554            // Keep track of app op permissions.
12555            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12556                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
12557                if (pkgs == null) {
12558                    pkgs = new ArraySet<>();
12559                    mAppOpPermissionPackages.put(bp.name, pkgs);
12560                }
12561                pkgs.add(pkg.packageName);
12562            }
12563
12564            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
12565            switch (level) {
12566                case PermissionInfo.PROTECTION_NORMAL: {
12567                    // For all apps normal permissions are install time ones.
12568                    grant = GRANT_INSTALL;
12569                } break;
12570
12571                case PermissionInfo.PROTECTION_DANGEROUS: {
12572                    // If a permission review is required for legacy apps we represent
12573                    // their permissions as always granted runtime ones since we need
12574                    // to keep the review required permission flag per user while an
12575                    // install permission's state is shared across all users.
12576                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
12577                        // For legacy apps dangerous permissions are install time ones.
12578                        grant = GRANT_INSTALL;
12579                    } else if (origPermissions.hasInstallPermission(bp.name)) {
12580                        // For legacy apps that became modern, install becomes runtime.
12581                        grant = GRANT_UPGRADE;
12582                    } else if (mPromoteSystemApps
12583                            && isSystemApp(ps)
12584                            && mExistingSystemPackages.contains(ps.name)) {
12585                        // For legacy system apps, install becomes runtime.
12586                        // We cannot check hasInstallPermission() for system apps since those
12587                        // permissions were granted implicitly and not persisted pre-M.
12588                        grant = GRANT_UPGRADE;
12589                    } else {
12590                        // For modern apps keep runtime permissions unchanged.
12591                        grant = GRANT_RUNTIME;
12592                    }
12593                } break;
12594
12595                case PermissionInfo.PROTECTION_SIGNATURE: {
12596                    // For all apps signature permissions are install time ones.
12597                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
12598                    if (allowedSig) {
12599                        grant = GRANT_INSTALL;
12600                    }
12601                } break;
12602            }
12603
12604            if (DEBUG_PERMISSIONS) {
12605                Slog.i(TAG, "Granting permission " + perm + " to package " + pkg.packageName);
12606            }
12607
12608            if (grant != GRANT_DENIED) {
12609                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
12610                    // If this is an existing, non-system package, then
12611                    // we can't add any new permissions to it.
12612                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
12613                        // Except...  if this is a permission that was added
12614                        // to the platform (note: need to only do this when
12615                        // updating the platform).
12616                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
12617                            grant = GRANT_DENIED;
12618                        }
12619                    }
12620                }
12621
12622                switch (grant) {
12623                    case GRANT_INSTALL: {
12624                        // Revoke this as runtime permission to handle the case of
12625                        // a runtime permission being downgraded to an install one.
12626                        // Also in permission review mode we keep dangerous permissions
12627                        // for legacy apps
12628                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12629                            if (origPermissions.getRuntimePermissionState(
12630                                    bp.name, userId) != null) {
12631                                // Revoke the runtime permission and clear the flags.
12632                                origPermissions.revokeRuntimePermission(bp, userId);
12633                                origPermissions.updatePermissionFlags(bp, userId,
12634                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
12635                                // If we revoked a permission permission, we have to write.
12636                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12637                                        changedRuntimePermissionUserIds, userId);
12638                            }
12639                        }
12640                        // Grant an install permission.
12641                        if (permissionsState.grantInstallPermission(bp) !=
12642                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
12643                            changedInstallPermission = true;
12644                        }
12645                    } break;
12646
12647                    case GRANT_RUNTIME: {
12648                        // Grant previously granted runtime permissions.
12649                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12650                            PermissionState permissionState = origPermissions
12651                                    .getRuntimePermissionState(bp.name, userId);
12652                            int flags = permissionState != null
12653                                    ? permissionState.getFlags() : 0;
12654                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
12655                                // Don't propagate the permission in a permission review mode if
12656                                // the former was revoked, i.e. marked to not propagate on upgrade.
12657                                // Note that in a permission review mode install permissions are
12658                                // represented as constantly granted runtime ones since we need to
12659                                // keep a per user state associated with the permission. Also the
12660                                // revoke on upgrade flag is no longer applicable and is reset.
12661                                final boolean revokeOnUpgrade = (flags & PackageManager
12662                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
12663                                if (revokeOnUpgrade) {
12664                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
12665                                    // Since we changed the flags, we have to write.
12666                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12667                                            changedRuntimePermissionUserIds, userId);
12668                                }
12669                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
12670                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
12671                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
12672                                        // If we cannot put the permission as it was,
12673                                        // we have to write.
12674                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12675                                                changedRuntimePermissionUserIds, userId);
12676                                    }
12677                                }
12678
12679                                // If the app supports runtime permissions no need for a review.
12680                                if (mPermissionReviewRequired
12681                                        && appSupportsRuntimePermissions
12682                                        && (flags & PackageManager
12683                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
12684                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
12685                                    // Since we changed the flags, we have to write.
12686                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12687                                            changedRuntimePermissionUserIds, userId);
12688                                }
12689                            } else if (mPermissionReviewRequired
12690                                    && !appSupportsRuntimePermissions) {
12691                                // For legacy apps that need a permission review, every new
12692                                // runtime permission is granted but it is pending a review.
12693                                // We also need to review only platform defined runtime
12694                                // permissions as these are the only ones the platform knows
12695                                // how to disable the API to simulate revocation as legacy
12696                                // apps don't expect to run with revoked permissions.
12697                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
12698                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
12699                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
12700                                        // We changed the flags, hence have to write.
12701                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12702                                                changedRuntimePermissionUserIds, userId);
12703                                    }
12704                                }
12705                                if (permissionsState.grantRuntimePermission(bp, userId)
12706                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
12707                                    // We changed the permission, hence have to write.
12708                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12709                                            changedRuntimePermissionUserIds, userId);
12710                                }
12711                            }
12712                            // Propagate the permission flags.
12713                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
12714                        }
12715                    } break;
12716
12717                    case GRANT_UPGRADE: {
12718                        // Grant runtime permissions for a previously held install permission.
12719                        PermissionState permissionState = origPermissions
12720                                .getInstallPermissionState(bp.name);
12721                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
12722
12723                        if (origPermissions.revokeInstallPermission(bp)
12724                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
12725                            // We will be transferring the permission flags, so clear them.
12726                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
12727                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
12728                            changedInstallPermission = true;
12729                        }
12730
12731                        // If the permission is not to be promoted to runtime we ignore it and
12732                        // also its other flags as they are not applicable to install permissions.
12733                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
12734                            for (int userId : currentUserIds) {
12735                                if (permissionsState.grantRuntimePermission(bp, userId) !=
12736                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
12737                                    // Transfer the permission flags.
12738                                    permissionsState.updatePermissionFlags(bp, userId,
12739                                            flags, flags);
12740                                    // If we granted the permission, we have to write.
12741                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12742                                            changedRuntimePermissionUserIds, userId);
12743                                }
12744                            }
12745                        }
12746                    } break;
12747
12748                    default: {
12749                        if (packageOfInterest == null
12750                                || packageOfInterest.equals(pkg.packageName)) {
12751                            if (DEBUG_PERMISSIONS) {
12752                                Slog.i(TAG, "Not granting permission " + perm
12753                                        + " to package " + pkg.packageName
12754                                        + " because it was previously installed without");
12755                            }
12756                        }
12757                    } break;
12758                }
12759            } else {
12760                if (permissionsState.revokeInstallPermission(bp) !=
12761                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
12762                    // Also drop the permission flags.
12763                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
12764                            PackageManager.MASK_PERMISSION_FLAGS, 0);
12765                    changedInstallPermission = true;
12766                    Slog.i(TAG, "Un-granting permission " + perm
12767                            + " from package " + pkg.packageName
12768                            + " (protectionLevel=" + bp.protectionLevel
12769                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
12770                            + ")");
12771                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
12772                    // Don't print warning for app op permissions, since it is fine for them
12773                    // not to be granted, there is a UI for the user to decide.
12774                    if (DEBUG_PERMISSIONS
12775                            && (packageOfInterest == null
12776                                    || packageOfInterest.equals(pkg.packageName))) {
12777                        Slog.i(TAG, "Not granting permission " + perm
12778                                + " to package " + pkg.packageName
12779                                + " (protectionLevel=" + bp.protectionLevel
12780                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
12781                                + ")");
12782                    }
12783                }
12784            }
12785        }
12786
12787        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
12788                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
12789            // This is the first that we have heard about this package, so the
12790            // permissions we have now selected are fixed until explicitly
12791            // changed.
12792            ps.installPermissionsFixed = true;
12793        }
12794
12795        // Persist the runtime permissions state for users with changes. If permissions
12796        // were revoked because no app in the shared user declares them we have to
12797        // write synchronously to avoid losing runtime permissions state.
12798        for (int userId : changedRuntimePermissionUserIds) {
12799            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
12800        }
12801    }
12802
12803    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
12804        boolean allowed = false;
12805        final int NP = PackageParser.NEW_PERMISSIONS.length;
12806        for (int ip=0; ip<NP; ip++) {
12807            final PackageParser.NewPermissionInfo npi
12808                    = PackageParser.NEW_PERMISSIONS[ip];
12809            if (npi.name.equals(perm)
12810                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
12811                allowed = true;
12812                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
12813                        + pkg.packageName);
12814                break;
12815            }
12816        }
12817        return allowed;
12818    }
12819
12820    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
12821            BasePermission bp, PermissionsState origPermissions) {
12822        boolean privilegedPermission = (bp.protectionLevel
12823                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
12824        boolean privappPermissionsDisable =
12825                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
12826        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
12827        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
12828        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
12829                && !platformPackage && platformPermission) {
12830            ArraySet<String> wlPermissions = SystemConfig.getInstance()
12831                    .getPrivAppPermissions(pkg.packageName);
12832            boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
12833            if (!whitelisted) {
12834                Slog.w(TAG, "Privileged permission " + perm + " for package "
12835                        + pkg.packageName + " - not in privapp-permissions whitelist");
12836                // Only report violations for apps on system image
12837                if (!mSystemReady && !pkg.isUpdatedSystemApp()) {
12838                    if (mPrivappPermissionsViolations == null) {
12839                        mPrivappPermissionsViolations = new ArraySet<>();
12840                    }
12841                    mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
12842                }
12843                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
12844                    return false;
12845                }
12846            }
12847        }
12848        boolean allowed = (compareSignatures(
12849                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
12850                        == PackageManager.SIGNATURE_MATCH)
12851                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
12852                        == PackageManager.SIGNATURE_MATCH);
12853        if (!allowed && privilegedPermission) {
12854            if (isSystemApp(pkg)) {
12855                // For updated system applications, a system permission
12856                // is granted only if it had been defined by the original application.
12857                if (pkg.isUpdatedSystemApp()) {
12858                    final PackageSetting sysPs = mSettings
12859                            .getDisabledSystemPkgLPr(pkg.packageName);
12860                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
12861                        // If the original was granted this permission, we take
12862                        // that grant decision as read and propagate it to the
12863                        // update.
12864                        if (sysPs.isPrivileged()) {
12865                            allowed = true;
12866                        }
12867                    } else {
12868                        // The system apk may have been updated with an older
12869                        // version of the one on the data partition, but which
12870                        // granted a new system permission that it didn't have
12871                        // before.  In this case we do want to allow the app to
12872                        // now get the new permission if the ancestral apk is
12873                        // privileged to get it.
12874                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
12875                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
12876                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
12877                                    allowed = true;
12878                                    break;
12879                                }
12880                            }
12881                        }
12882                        // Also if a privileged parent package on the system image or any of
12883                        // its children requested a privileged permission, the updated child
12884                        // packages can also get the permission.
12885                        if (pkg.parentPackage != null) {
12886                            final PackageSetting disabledSysParentPs = mSettings
12887                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
12888                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
12889                                    && disabledSysParentPs.isPrivileged()) {
12890                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
12891                                    allowed = true;
12892                                } else if (disabledSysParentPs.pkg.childPackages != null) {
12893                                    final int count = disabledSysParentPs.pkg.childPackages.size();
12894                                    for (int i = 0; i < count; i++) {
12895                                        PackageParser.Package disabledSysChildPkg =
12896                                                disabledSysParentPs.pkg.childPackages.get(i);
12897                                        if (isPackageRequestingPermission(disabledSysChildPkg,
12898                                                perm)) {
12899                                            allowed = true;
12900                                            break;
12901                                        }
12902                                    }
12903                                }
12904                            }
12905                        }
12906                    }
12907                } else {
12908                    allowed = isPrivilegedApp(pkg);
12909                }
12910            }
12911        }
12912        if (!allowed) {
12913            if (!allowed && (bp.protectionLevel
12914                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
12915                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
12916                // If this was a previously normal/dangerous permission that got moved
12917                // to a system permission as part of the runtime permission redesign, then
12918                // we still want to blindly grant it to old apps.
12919                allowed = true;
12920            }
12921            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
12922                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
12923                // If this permission is to be granted to the system installer and
12924                // this app is an installer, then it gets the permission.
12925                allowed = true;
12926            }
12927            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
12928                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
12929                // If this permission is to be granted to the system verifier and
12930                // this app is a verifier, then it gets the permission.
12931                allowed = true;
12932            }
12933            if (!allowed && (bp.protectionLevel
12934                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
12935                    && isSystemApp(pkg)) {
12936                // Any pre-installed system app is allowed to get this permission.
12937                allowed = true;
12938            }
12939            if (!allowed && (bp.protectionLevel
12940                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
12941                // For development permissions, a development permission
12942                // is granted only if it was already granted.
12943                allowed = origPermissions.hasInstallPermission(perm);
12944            }
12945            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
12946                    && pkg.packageName.equals(mSetupWizardPackage)) {
12947                // If this permission is to be granted to the system setup wizard and
12948                // this app is a setup wizard, then it gets the permission.
12949                allowed = true;
12950            }
12951        }
12952        return allowed;
12953    }
12954
12955    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
12956        final int permCount = pkg.requestedPermissions.size();
12957        for (int j = 0; j < permCount; j++) {
12958            String requestedPermission = pkg.requestedPermissions.get(j);
12959            if (permission.equals(requestedPermission)) {
12960                return true;
12961            }
12962        }
12963        return false;
12964    }
12965
12966    final class ActivityIntentResolver
12967            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
12968        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12969                boolean defaultOnly, int userId) {
12970            if (!sUserManager.exists(userId)) return null;
12971            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
12972            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12973        }
12974
12975        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12976                int userId) {
12977            if (!sUserManager.exists(userId)) return null;
12978            mFlags = flags;
12979            return super.queryIntent(intent, resolvedType,
12980                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12981                    userId);
12982        }
12983
12984        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12985                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
12986            if (!sUserManager.exists(userId)) return null;
12987            if (packageActivities == null) {
12988                return null;
12989            }
12990            mFlags = flags;
12991            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12992            final int N = packageActivities.size();
12993            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
12994                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
12995
12996            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
12997            for (int i = 0; i < N; ++i) {
12998                intentFilters = packageActivities.get(i).intents;
12999                if (intentFilters != null && intentFilters.size() > 0) {
13000                    PackageParser.ActivityIntentInfo[] array =
13001                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
13002                    intentFilters.toArray(array);
13003                    listCut.add(array);
13004                }
13005            }
13006            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13007        }
13008
13009        /**
13010         * Finds a privileged activity that matches the specified activity names.
13011         */
13012        private PackageParser.Activity findMatchingActivity(
13013                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
13014            for (PackageParser.Activity sysActivity : activityList) {
13015                if (sysActivity.info.name.equals(activityInfo.name)) {
13016                    return sysActivity;
13017                }
13018                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
13019                    return sysActivity;
13020                }
13021                if (sysActivity.info.targetActivity != null) {
13022                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
13023                        return sysActivity;
13024                    }
13025                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
13026                        return sysActivity;
13027                    }
13028                }
13029            }
13030            return null;
13031        }
13032
13033        public class IterGenerator<E> {
13034            public Iterator<E> generate(ActivityIntentInfo info) {
13035                return null;
13036            }
13037        }
13038
13039        public class ActionIterGenerator extends IterGenerator<String> {
13040            @Override
13041            public Iterator<String> generate(ActivityIntentInfo info) {
13042                return info.actionsIterator();
13043            }
13044        }
13045
13046        public class CategoriesIterGenerator extends IterGenerator<String> {
13047            @Override
13048            public Iterator<String> generate(ActivityIntentInfo info) {
13049                return info.categoriesIterator();
13050            }
13051        }
13052
13053        public class SchemesIterGenerator extends IterGenerator<String> {
13054            @Override
13055            public Iterator<String> generate(ActivityIntentInfo info) {
13056                return info.schemesIterator();
13057            }
13058        }
13059
13060        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
13061            @Override
13062            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
13063                return info.authoritiesIterator();
13064            }
13065        }
13066
13067        /**
13068         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
13069         * MODIFIED. Do not pass in a list that should not be changed.
13070         */
13071        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
13072                IterGenerator<T> generator, Iterator<T> searchIterator) {
13073            // loop through the set of actions; every one must be found in the intent filter
13074            while (searchIterator.hasNext()) {
13075                // we must have at least one filter in the list to consider a match
13076                if (intentList.size() == 0) {
13077                    break;
13078                }
13079
13080                final T searchAction = searchIterator.next();
13081
13082                // loop through the set of intent filters
13083                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
13084                while (intentIter.hasNext()) {
13085                    final ActivityIntentInfo intentInfo = intentIter.next();
13086                    boolean selectionFound = false;
13087
13088                    // loop through the intent filter's selection criteria; at least one
13089                    // of them must match the searched criteria
13090                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
13091                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
13092                        final T intentSelection = intentSelectionIter.next();
13093                        if (intentSelection != null && intentSelection.equals(searchAction)) {
13094                            selectionFound = true;
13095                            break;
13096                        }
13097                    }
13098
13099                    // the selection criteria wasn't found in this filter's set; this filter
13100                    // is not a potential match
13101                    if (!selectionFound) {
13102                        intentIter.remove();
13103                    }
13104                }
13105            }
13106        }
13107
13108        private boolean isProtectedAction(ActivityIntentInfo filter) {
13109            final Iterator<String> actionsIter = filter.actionsIterator();
13110            while (actionsIter != null && actionsIter.hasNext()) {
13111                final String filterAction = actionsIter.next();
13112                if (PROTECTED_ACTIONS.contains(filterAction)) {
13113                    return true;
13114                }
13115            }
13116            return false;
13117        }
13118
13119        /**
13120         * Adjusts the priority of the given intent filter according to policy.
13121         * <p>
13122         * <ul>
13123         * <li>The priority for non privileged applications is capped to '0'</li>
13124         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
13125         * <li>The priority for unbundled updates to privileged applications is capped to the
13126         *      priority defined on the system partition</li>
13127         * </ul>
13128         * <p>
13129         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
13130         * allowed to obtain any priority on any action.
13131         */
13132        private void adjustPriority(
13133                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
13134            // nothing to do; priority is fine as-is
13135            if (intent.getPriority() <= 0) {
13136                return;
13137            }
13138
13139            final ActivityInfo activityInfo = intent.activity.info;
13140            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
13141
13142            final boolean privilegedApp =
13143                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
13144            if (!privilegedApp) {
13145                // non-privileged applications can never define a priority >0
13146                if (DEBUG_FILTERS) {
13147                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
13148                            + " package: " + applicationInfo.packageName
13149                            + " activity: " + intent.activity.className
13150                            + " origPrio: " + intent.getPriority());
13151                }
13152                intent.setPriority(0);
13153                return;
13154            }
13155
13156            if (systemActivities == null) {
13157                // the system package is not disabled; we're parsing the system partition
13158                if (isProtectedAction(intent)) {
13159                    if (mDeferProtectedFilters) {
13160                        // We can't deal with these just yet. No component should ever obtain a
13161                        // >0 priority for a protected actions, with ONE exception -- the setup
13162                        // wizard. The setup wizard, however, cannot be known until we're able to
13163                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
13164                        // until all intent filters have been processed. Chicken, meet egg.
13165                        // Let the filter temporarily have a high priority and rectify the
13166                        // priorities after all system packages have been scanned.
13167                        mProtectedFilters.add(intent);
13168                        if (DEBUG_FILTERS) {
13169                            Slog.i(TAG, "Protected action; save for later;"
13170                                    + " package: " + applicationInfo.packageName
13171                                    + " activity: " + intent.activity.className
13172                                    + " origPrio: " + intent.getPriority());
13173                        }
13174                        return;
13175                    } else {
13176                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
13177                            Slog.i(TAG, "No setup wizard;"
13178                                + " All protected intents capped to priority 0");
13179                        }
13180                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
13181                            if (DEBUG_FILTERS) {
13182                                Slog.i(TAG, "Found setup wizard;"
13183                                    + " allow priority " + intent.getPriority() + ";"
13184                                    + " package: " + intent.activity.info.packageName
13185                                    + " activity: " + intent.activity.className
13186                                    + " priority: " + intent.getPriority());
13187                            }
13188                            // setup wizard gets whatever it wants
13189                            return;
13190                        }
13191                        if (DEBUG_FILTERS) {
13192                            Slog.i(TAG, "Protected action; cap priority to 0;"
13193                                    + " package: " + intent.activity.info.packageName
13194                                    + " activity: " + intent.activity.className
13195                                    + " origPrio: " + intent.getPriority());
13196                        }
13197                        intent.setPriority(0);
13198                        return;
13199                    }
13200                }
13201                // privileged apps on the system image get whatever priority they request
13202                return;
13203            }
13204
13205            // privileged app unbundled update ... try to find the same activity
13206            final PackageParser.Activity foundActivity =
13207                    findMatchingActivity(systemActivities, activityInfo);
13208            if (foundActivity == null) {
13209                // this is a new activity; it cannot obtain >0 priority
13210                if (DEBUG_FILTERS) {
13211                    Slog.i(TAG, "New activity; 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            // found activity, now check for filter equivalence
13221
13222            // a shallow copy is enough; we modify the list, not its contents
13223            final List<ActivityIntentInfo> intentListCopy =
13224                    new ArrayList<>(foundActivity.intents);
13225            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
13226
13227            // find matching action subsets
13228            final Iterator<String> actionsIterator = intent.actionsIterator();
13229            if (actionsIterator != null) {
13230                getIntentListSubset(
13231                        intentListCopy, new ActionIterGenerator(), actionsIterator);
13232                if (intentListCopy.size() == 0) {
13233                    // no more intents to match; we're not equivalent
13234                    if (DEBUG_FILTERS) {
13235                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
13236                                + " package: " + applicationInfo.packageName
13237                                + " activity: " + intent.activity.className
13238                                + " origPrio: " + intent.getPriority());
13239                    }
13240                    intent.setPriority(0);
13241                    return;
13242                }
13243            }
13244
13245            // find matching category subsets
13246            final Iterator<String> categoriesIterator = intent.categoriesIterator();
13247            if (categoriesIterator != null) {
13248                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
13249                        categoriesIterator);
13250                if (intentListCopy.size() == 0) {
13251                    // no more intents to match; we're not equivalent
13252                    if (DEBUG_FILTERS) {
13253                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
13254                                + " package: " + applicationInfo.packageName
13255                                + " activity: " + intent.activity.className
13256                                + " origPrio: " + intent.getPriority());
13257                    }
13258                    intent.setPriority(0);
13259                    return;
13260                }
13261            }
13262
13263            // find matching schemes subsets
13264            final Iterator<String> schemesIterator = intent.schemesIterator();
13265            if (schemesIterator != null) {
13266                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
13267                        schemesIterator);
13268                if (intentListCopy.size() == 0) {
13269                    // no more intents to match; we're not equivalent
13270                    if (DEBUG_FILTERS) {
13271                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
13272                                + " package: " + applicationInfo.packageName
13273                                + " activity: " + intent.activity.className
13274                                + " origPrio: " + intent.getPriority());
13275                    }
13276                    intent.setPriority(0);
13277                    return;
13278                }
13279            }
13280
13281            // find matching authorities subsets
13282            final Iterator<IntentFilter.AuthorityEntry>
13283                    authoritiesIterator = intent.authoritiesIterator();
13284            if (authoritiesIterator != null) {
13285                getIntentListSubset(intentListCopy,
13286                        new AuthoritiesIterGenerator(),
13287                        authoritiesIterator);
13288                if (intentListCopy.size() == 0) {
13289                    // no more intents to match; we're not equivalent
13290                    if (DEBUG_FILTERS) {
13291                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
13292                                + " package: " + applicationInfo.packageName
13293                                + " activity: " + intent.activity.className
13294                                + " origPrio: " + intent.getPriority());
13295                    }
13296                    intent.setPriority(0);
13297                    return;
13298                }
13299            }
13300
13301            // we found matching filter(s); app gets the max priority of all intents
13302            int cappedPriority = 0;
13303            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
13304                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
13305            }
13306            if (intent.getPriority() > cappedPriority) {
13307                if (DEBUG_FILTERS) {
13308                    Slog.i(TAG, "Found matching filter(s);"
13309                            + " cap priority to " + cappedPriority + ";"
13310                            + " package: " + applicationInfo.packageName
13311                            + " activity: " + intent.activity.className
13312                            + " origPrio: " + intent.getPriority());
13313                }
13314                intent.setPriority(cappedPriority);
13315                return;
13316            }
13317            // all this for nothing; the requested priority was <= what was on the system
13318        }
13319
13320        public final void addActivity(PackageParser.Activity a, String type) {
13321            mActivities.put(a.getComponentName(), a);
13322            if (DEBUG_SHOW_INFO)
13323                Log.v(
13324                TAG, "  " + type + " " +
13325                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
13326            if (DEBUG_SHOW_INFO)
13327                Log.v(TAG, "    Class=" + a.info.name);
13328            final int NI = a.intents.size();
13329            for (int j=0; j<NI; j++) {
13330                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13331                if ("activity".equals(type)) {
13332                    final PackageSetting ps =
13333                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
13334                    final List<PackageParser.Activity> systemActivities =
13335                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
13336                    adjustPriority(systemActivities, intent);
13337                }
13338                if (DEBUG_SHOW_INFO) {
13339                    Log.v(TAG, "    IntentFilter:");
13340                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13341                }
13342                if (!intent.debugCheck()) {
13343                    Log.w(TAG, "==> For Activity " + a.info.name);
13344                }
13345                addFilter(intent);
13346            }
13347        }
13348
13349        public final void removeActivity(PackageParser.Activity a, String type) {
13350            mActivities.remove(a.getComponentName());
13351            if (DEBUG_SHOW_INFO) {
13352                Log.v(TAG, "  " + type + " "
13353                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
13354                                : a.info.name) + ":");
13355                Log.v(TAG, "    Class=" + a.info.name);
13356            }
13357            final int NI = a.intents.size();
13358            for (int j=0; j<NI; j++) {
13359                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13360                if (DEBUG_SHOW_INFO) {
13361                    Log.v(TAG, "    IntentFilter:");
13362                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13363                }
13364                removeFilter(intent);
13365            }
13366        }
13367
13368        @Override
13369        protected boolean allowFilterResult(
13370                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
13371            ActivityInfo filterAi = filter.activity.info;
13372            for (int i=dest.size()-1; i>=0; i--) {
13373                ActivityInfo destAi = dest.get(i).activityInfo;
13374                if (destAi.name == filterAi.name
13375                        && destAi.packageName == filterAi.packageName) {
13376                    return false;
13377                }
13378            }
13379            return true;
13380        }
13381
13382        @Override
13383        protected ActivityIntentInfo[] newArray(int size) {
13384            return new ActivityIntentInfo[size];
13385        }
13386
13387        @Override
13388        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
13389            if (!sUserManager.exists(userId)) return true;
13390            PackageParser.Package p = filter.activity.owner;
13391            if (p != null) {
13392                PackageSetting ps = (PackageSetting)p.mExtras;
13393                if (ps != null) {
13394                    // System apps are never considered stopped for purposes of
13395                    // filtering, because there may be no way for the user to
13396                    // actually re-launch them.
13397                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
13398                            && ps.getStopped(userId);
13399                }
13400            }
13401            return false;
13402        }
13403
13404        @Override
13405        protected boolean isPackageForFilter(String packageName,
13406                PackageParser.ActivityIntentInfo info) {
13407            return packageName.equals(info.activity.owner.packageName);
13408        }
13409
13410        @Override
13411        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
13412                int match, int userId) {
13413            if (!sUserManager.exists(userId)) return null;
13414            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
13415                return null;
13416            }
13417            final PackageParser.Activity activity = info.activity;
13418            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
13419            if (ps == null) {
13420                return null;
13421            }
13422            final PackageUserState userState = ps.readUserState(userId);
13423            ActivityInfo ai =
13424                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
13425            if (ai == null) {
13426                return null;
13427            }
13428            final boolean matchExplicitlyVisibleOnly =
13429                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
13430            final boolean matchVisibleToInstantApp =
13431                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13432            final boolean componentVisible =
13433                    matchVisibleToInstantApp
13434                    && info.isVisibleToInstantApp()
13435                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
13436            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13437            // throw out filters that aren't visible to ephemeral apps
13438            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
13439                return null;
13440            }
13441            // throw out instant app filters if we're not explicitly requesting them
13442            if (!matchInstantApp && userState.instantApp) {
13443                return null;
13444            }
13445            // throw out instant app filters if updates are available; will trigger
13446            // instant app resolution
13447            if (userState.instantApp && ps.isUpdateAvailable()) {
13448                return null;
13449            }
13450            final ResolveInfo res = new ResolveInfo();
13451            res.activityInfo = ai;
13452            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13453                res.filter = info;
13454            }
13455            if (info != null) {
13456                res.handleAllWebDataURI = info.handleAllWebDataURI();
13457            }
13458            res.priority = info.getPriority();
13459            res.preferredOrder = activity.owner.mPreferredOrder;
13460            //System.out.println("Result: " + res.activityInfo.className +
13461            //                   " = " + res.priority);
13462            res.match = match;
13463            res.isDefault = info.hasDefault;
13464            res.labelRes = info.labelRes;
13465            res.nonLocalizedLabel = info.nonLocalizedLabel;
13466            if (userNeedsBadging(userId)) {
13467                res.noResourceId = true;
13468            } else {
13469                res.icon = info.icon;
13470            }
13471            res.iconResourceId = info.icon;
13472            res.system = res.activityInfo.applicationInfo.isSystemApp();
13473            res.isInstantAppAvailable = userState.instantApp;
13474            return res;
13475        }
13476
13477        @Override
13478        protected void sortResults(List<ResolveInfo> results) {
13479            Collections.sort(results, mResolvePrioritySorter);
13480        }
13481
13482        @Override
13483        protected void dumpFilter(PrintWriter out, String prefix,
13484                PackageParser.ActivityIntentInfo filter) {
13485            out.print(prefix); out.print(
13486                    Integer.toHexString(System.identityHashCode(filter.activity)));
13487                    out.print(' ');
13488                    filter.activity.printComponentShortName(out);
13489                    out.print(" filter ");
13490                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13491        }
13492
13493        @Override
13494        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
13495            return filter.activity;
13496        }
13497
13498        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13499            PackageParser.Activity activity = (PackageParser.Activity)label;
13500            out.print(prefix); out.print(
13501                    Integer.toHexString(System.identityHashCode(activity)));
13502                    out.print(' ');
13503                    activity.printComponentShortName(out);
13504            if (count > 1) {
13505                out.print(" ("); out.print(count); out.print(" filters)");
13506            }
13507            out.println();
13508        }
13509
13510        // Keys are String (activity class name), values are Activity.
13511        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
13512                = new ArrayMap<ComponentName, PackageParser.Activity>();
13513        private int mFlags;
13514    }
13515
13516    private final class ServiceIntentResolver
13517            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
13518        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13519                boolean defaultOnly, int userId) {
13520            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13521            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13522        }
13523
13524        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13525                int userId) {
13526            if (!sUserManager.exists(userId)) return null;
13527            mFlags = flags;
13528            return super.queryIntent(intent, resolvedType,
13529                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13530                    userId);
13531        }
13532
13533        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13534                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
13535            if (!sUserManager.exists(userId)) return null;
13536            if (packageServices == null) {
13537                return null;
13538            }
13539            mFlags = flags;
13540            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
13541            final int N = packageServices.size();
13542            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
13543                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
13544
13545            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
13546            for (int i = 0; i < N; ++i) {
13547                intentFilters = packageServices.get(i).intents;
13548                if (intentFilters != null && intentFilters.size() > 0) {
13549                    PackageParser.ServiceIntentInfo[] array =
13550                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
13551                    intentFilters.toArray(array);
13552                    listCut.add(array);
13553                }
13554            }
13555            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13556        }
13557
13558        public final void addService(PackageParser.Service s) {
13559            mServices.put(s.getComponentName(), s);
13560            if (DEBUG_SHOW_INFO) {
13561                Log.v(TAG, "  "
13562                        + (s.info.nonLocalizedLabel != null
13563                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13564                Log.v(TAG, "    Class=" + s.info.name);
13565            }
13566            final int NI = s.intents.size();
13567            int j;
13568            for (j=0; j<NI; j++) {
13569                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13570                if (DEBUG_SHOW_INFO) {
13571                    Log.v(TAG, "    IntentFilter:");
13572                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13573                }
13574                if (!intent.debugCheck()) {
13575                    Log.w(TAG, "==> For Service " + s.info.name);
13576                }
13577                addFilter(intent);
13578            }
13579        }
13580
13581        public final void removeService(PackageParser.Service s) {
13582            mServices.remove(s.getComponentName());
13583            if (DEBUG_SHOW_INFO) {
13584                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
13585                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13586                Log.v(TAG, "    Class=" + s.info.name);
13587            }
13588            final int NI = s.intents.size();
13589            int j;
13590            for (j=0; j<NI; j++) {
13591                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13592                if (DEBUG_SHOW_INFO) {
13593                    Log.v(TAG, "    IntentFilter:");
13594                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13595                }
13596                removeFilter(intent);
13597            }
13598        }
13599
13600        @Override
13601        protected boolean allowFilterResult(
13602                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
13603            ServiceInfo filterSi = filter.service.info;
13604            for (int i=dest.size()-1; i>=0; i--) {
13605                ServiceInfo destAi = dest.get(i).serviceInfo;
13606                if (destAi.name == filterSi.name
13607                        && destAi.packageName == filterSi.packageName) {
13608                    return false;
13609                }
13610            }
13611            return true;
13612        }
13613
13614        @Override
13615        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
13616            return new PackageParser.ServiceIntentInfo[size];
13617        }
13618
13619        @Override
13620        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
13621            if (!sUserManager.exists(userId)) return true;
13622            PackageParser.Package p = filter.service.owner;
13623            if (p != null) {
13624                PackageSetting ps = (PackageSetting)p.mExtras;
13625                if (ps != null) {
13626                    // System apps are never considered stopped for purposes of
13627                    // filtering, because there may be no way for the user to
13628                    // actually re-launch them.
13629                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13630                            && ps.getStopped(userId);
13631                }
13632            }
13633            return false;
13634        }
13635
13636        @Override
13637        protected boolean isPackageForFilter(String packageName,
13638                PackageParser.ServiceIntentInfo info) {
13639            return packageName.equals(info.service.owner.packageName);
13640        }
13641
13642        @Override
13643        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
13644                int match, int userId) {
13645            if (!sUserManager.exists(userId)) return null;
13646            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
13647            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
13648                return null;
13649            }
13650            final PackageParser.Service service = info.service;
13651            PackageSetting ps = (PackageSetting) service.owner.mExtras;
13652            if (ps == null) {
13653                return null;
13654            }
13655            final PackageUserState userState = ps.readUserState(userId);
13656            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
13657                    userState, userId);
13658            if (si == null) {
13659                return null;
13660            }
13661            final boolean matchVisibleToInstantApp =
13662                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13663            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13664            // throw out filters that aren't visible to ephemeral apps
13665            if (matchVisibleToInstantApp
13666                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13667                return null;
13668            }
13669            // throw out ephemeral filters if we're not explicitly requesting them
13670            if (!isInstantApp && userState.instantApp) {
13671                return null;
13672            }
13673            // throw out instant app filters if updates are available; will trigger
13674            // instant app resolution
13675            if (userState.instantApp && ps.isUpdateAvailable()) {
13676                return null;
13677            }
13678            final ResolveInfo res = new ResolveInfo();
13679            res.serviceInfo = si;
13680            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13681                res.filter = filter;
13682            }
13683            res.priority = info.getPriority();
13684            res.preferredOrder = service.owner.mPreferredOrder;
13685            res.match = match;
13686            res.isDefault = info.hasDefault;
13687            res.labelRes = info.labelRes;
13688            res.nonLocalizedLabel = info.nonLocalizedLabel;
13689            res.icon = info.icon;
13690            res.system = res.serviceInfo.applicationInfo.isSystemApp();
13691            return res;
13692        }
13693
13694        @Override
13695        protected void sortResults(List<ResolveInfo> results) {
13696            Collections.sort(results, mResolvePrioritySorter);
13697        }
13698
13699        @Override
13700        protected void dumpFilter(PrintWriter out, String prefix,
13701                PackageParser.ServiceIntentInfo filter) {
13702            out.print(prefix); out.print(
13703                    Integer.toHexString(System.identityHashCode(filter.service)));
13704                    out.print(' ');
13705                    filter.service.printComponentShortName(out);
13706                    out.print(" filter ");
13707                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13708        }
13709
13710        @Override
13711        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
13712            return filter.service;
13713        }
13714
13715        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13716            PackageParser.Service service = (PackageParser.Service)label;
13717            out.print(prefix); out.print(
13718                    Integer.toHexString(System.identityHashCode(service)));
13719                    out.print(' ');
13720                    service.printComponentShortName(out);
13721            if (count > 1) {
13722                out.print(" ("); out.print(count); out.print(" filters)");
13723            }
13724            out.println();
13725        }
13726
13727//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
13728//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
13729//            final List<ResolveInfo> retList = Lists.newArrayList();
13730//            while (i.hasNext()) {
13731//                final ResolveInfo resolveInfo = (ResolveInfo) i;
13732//                if (isEnabledLP(resolveInfo.serviceInfo)) {
13733//                    retList.add(resolveInfo);
13734//                }
13735//            }
13736//            return retList;
13737//        }
13738
13739        // Keys are String (activity class name), values are Activity.
13740        private final ArrayMap<ComponentName, PackageParser.Service> mServices
13741                = new ArrayMap<ComponentName, PackageParser.Service>();
13742        private int mFlags;
13743    }
13744
13745    private final class ProviderIntentResolver
13746            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
13747        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13748                boolean defaultOnly, int userId) {
13749            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13750            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13751        }
13752
13753        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13754                int userId) {
13755            if (!sUserManager.exists(userId))
13756                return null;
13757            mFlags = flags;
13758            return super.queryIntent(intent, resolvedType,
13759                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13760                    userId);
13761        }
13762
13763        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13764                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
13765            if (!sUserManager.exists(userId))
13766                return null;
13767            if (packageProviders == null) {
13768                return null;
13769            }
13770            mFlags = flags;
13771            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
13772            final int N = packageProviders.size();
13773            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
13774                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
13775
13776            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
13777            for (int i = 0; i < N; ++i) {
13778                intentFilters = packageProviders.get(i).intents;
13779                if (intentFilters != null && intentFilters.size() > 0) {
13780                    PackageParser.ProviderIntentInfo[] array =
13781                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
13782                    intentFilters.toArray(array);
13783                    listCut.add(array);
13784                }
13785            }
13786            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13787        }
13788
13789        public final void addProvider(PackageParser.Provider p) {
13790            if (mProviders.containsKey(p.getComponentName())) {
13791                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
13792                return;
13793            }
13794
13795            mProviders.put(p.getComponentName(), p);
13796            if (DEBUG_SHOW_INFO) {
13797                Log.v(TAG, "  "
13798                        + (p.info.nonLocalizedLabel != null
13799                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
13800                Log.v(TAG, "    Class=" + p.info.name);
13801            }
13802            final int NI = p.intents.size();
13803            int j;
13804            for (j = 0; j < NI; j++) {
13805                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13806                if (DEBUG_SHOW_INFO) {
13807                    Log.v(TAG, "    IntentFilter:");
13808                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13809                }
13810                if (!intent.debugCheck()) {
13811                    Log.w(TAG, "==> For Provider " + p.info.name);
13812                }
13813                addFilter(intent);
13814            }
13815        }
13816
13817        public final void removeProvider(PackageParser.Provider p) {
13818            mProviders.remove(p.getComponentName());
13819            if (DEBUG_SHOW_INFO) {
13820                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
13821                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
13822                Log.v(TAG, "    Class=" + p.info.name);
13823            }
13824            final int NI = p.intents.size();
13825            int j;
13826            for (j = 0; j < NI; j++) {
13827                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13828                if (DEBUG_SHOW_INFO) {
13829                    Log.v(TAG, "    IntentFilter:");
13830                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13831                }
13832                removeFilter(intent);
13833            }
13834        }
13835
13836        @Override
13837        protected boolean allowFilterResult(
13838                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
13839            ProviderInfo filterPi = filter.provider.info;
13840            for (int i = dest.size() - 1; i >= 0; i--) {
13841                ProviderInfo destPi = dest.get(i).providerInfo;
13842                if (destPi.name == filterPi.name
13843                        && destPi.packageName == filterPi.packageName) {
13844                    return false;
13845                }
13846            }
13847            return true;
13848        }
13849
13850        @Override
13851        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
13852            return new PackageParser.ProviderIntentInfo[size];
13853        }
13854
13855        @Override
13856        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
13857            if (!sUserManager.exists(userId))
13858                return true;
13859            PackageParser.Package p = filter.provider.owner;
13860            if (p != null) {
13861                PackageSetting ps = (PackageSetting) p.mExtras;
13862                if (ps != null) {
13863                    // System apps are never considered stopped for purposes of
13864                    // filtering, because there may be no way for the user to
13865                    // actually re-launch them.
13866                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13867                            && ps.getStopped(userId);
13868                }
13869            }
13870            return false;
13871        }
13872
13873        @Override
13874        protected boolean isPackageForFilter(String packageName,
13875                PackageParser.ProviderIntentInfo info) {
13876            return packageName.equals(info.provider.owner.packageName);
13877        }
13878
13879        @Override
13880        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
13881                int match, int userId) {
13882            if (!sUserManager.exists(userId))
13883                return null;
13884            final PackageParser.ProviderIntentInfo info = filter;
13885            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
13886                return null;
13887            }
13888            final PackageParser.Provider provider = info.provider;
13889            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
13890            if (ps == null) {
13891                return null;
13892            }
13893            final PackageUserState userState = ps.readUserState(userId);
13894            final boolean matchVisibleToInstantApp =
13895                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13896            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13897            // throw out filters that aren't visible to instant applications
13898            if (matchVisibleToInstantApp
13899                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13900                return null;
13901            }
13902            // throw out instant application filters if we're not explicitly requesting them
13903            if (!isInstantApp && userState.instantApp) {
13904                return null;
13905            }
13906            // throw out instant application filters if updates are available; will trigger
13907            // instant application resolution
13908            if (userState.instantApp && ps.isUpdateAvailable()) {
13909                return null;
13910            }
13911            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
13912                    userState, userId);
13913            if (pi == null) {
13914                return null;
13915            }
13916            final ResolveInfo res = new ResolveInfo();
13917            res.providerInfo = pi;
13918            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
13919                res.filter = filter;
13920            }
13921            res.priority = info.getPriority();
13922            res.preferredOrder = provider.owner.mPreferredOrder;
13923            res.match = match;
13924            res.isDefault = info.hasDefault;
13925            res.labelRes = info.labelRes;
13926            res.nonLocalizedLabel = info.nonLocalizedLabel;
13927            res.icon = info.icon;
13928            res.system = res.providerInfo.applicationInfo.isSystemApp();
13929            return res;
13930        }
13931
13932        @Override
13933        protected void sortResults(List<ResolveInfo> results) {
13934            Collections.sort(results, mResolvePrioritySorter);
13935        }
13936
13937        @Override
13938        protected void dumpFilter(PrintWriter out, String prefix,
13939                PackageParser.ProviderIntentInfo filter) {
13940            out.print(prefix);
13941            out.print(
13942                    Integer.toHexString(System.identityHashCode(filter.provider)));
13943            out.print(' ');
13944            filter.provider.printComponentShortName(out);
13945            out.print(" filter ");
13946            out.println(Integer.toHexString(System.identityHashCode(filter)));
13947        }
13948
13949        @Override
13950        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
13951            return filter.provider;
13952        }
13953
13954        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13955            PackageParser.Provider provider = (PackageParser.Provider)label;
13956            out.print(prefix); out.print(
13957                    Integer.toHexString(System.identityHashCode(provider)));
13958                    out.print(' ');
13959                    provider.printComponentShortName(out);
13960            if (count > 1) {
13961                out.print(" ("); out.print(count); out.print(" filters)");
13962            }
13963            out.println();
13964        }
13965
13966        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
13967                = new ArrayMap<ComponentName, PackageParser.Provider>();
13968        private int mFlags;
13969    }
13970
13971    static final class EphemeralIntentResolver
13972            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
13973        /**
13974         * The result that has the highest defined order. Ordering applies on a
13975         * per-package basis. Mapping is from package name to Pair of order and
13976         * EphemeralResolveInfo.
13977         * <p>
13978         * NOTE: This is implemented as a field variable for convenience and efficiency.
13979         * By having a field variable, we're able to track filter ordering as soon as
13980         * a non-zero order is defined. Otherwise, multiple loops across the result set
13981         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
13982         * this needs to be contained entirely within {@link #filterResults}.
13983         */
13984        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
13985
13986        @Override
13987        protected AuxiliaryResolveInfo[] newArray(int size) {
13988            return new AuxiliaryResolveInfo[size];
13989        }
13990
13991        @Override
13992        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
13993            return true;
13994        }
13995
13996        @Override
13997        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
13998                int userId) {
13999            if (!sUserManager.exists(userId)) {
14000                return null;
14001            }
14002            final String packageName = responseObj.resolveInfo.getPackageName();
14003            final Integer order = responseObj.getOrder();
14004            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
14005                    mOrderResult.get(packageName);
14006            // ordering is enabled and this item's order isn't high enough
14007            if (lastOrderResult != null && lastOrderResult.first >= order) {
14008                return null;
14009            }
14010            final InstantAppResolveInfo res = responseObj.resolveInfo;
14011            if (order > 0) {
14012                // non-zero order, enable ordering
14013                mOrderResult.put(packageName, new Pair<>(order, res));
14014            }
14015            return responseObj;
14016        }
14017
14018        @Override
14019        protected void filterResults(List<AuxiliaryResolveInfo> results) {
14020            // only do work if ordering is enabled [most of the time it won't be]
14021            if (mOrderResult.size() == 0) {
14022                return;
14023            }
14024            int resultSize = results.size();
14025            for (int i = 0; i < resultSize; i++) {
14026                final InstantAppResolveInfo info = results.get(i).resolveInfo;
14027                final String packageName = info.getPackageName();
14028                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
14029                if (savedInfo == null) {
14030                    // package doesn't having ordering
14031                    continue;
14032                }
14033                if (savedInfo.second == info) {
14034                    // circled back to the highest ordered item; remove from order list
14035                    mOrderResult.remove(savedInfo);
14036                    if (mOrderResult.size() == 0) {
14037                        // no more ordered items
14038                        break;
14039                    }
14040                    continue;
14041                }
14042                // item has a worse order, remove it from the result list
14043                results.remove(i);
14044                resultSize--;
14045                i--;
14046            }
14047        }
14048    }
14049
14050    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
14051            new Comparator<ResolveInfo>() {
14052        public int compare(ResolveInfo r1, ResolveInfo r2) {
14053            int v1 = r1.priority;
14054            int v2 = r2.priority;
14055            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
14056            if (v1 != v2) {
14057                return (v1 > v2) ? -1 : 1;
14058            }
14059            v1 = r1.preferredOrder;
14060            v2 = r2.preferredOrder;
14061            if (v1 != v2) {
14062                return (v1 > v2) ? -1 : 1;
14063            }
14064            if (r1.isDefault != r2.isDefault) {
14065                return r1.isDefault ? -1 : 1;
14066            }
14067            v1 = r1.match;
14068            v2 = r2.match;
14069            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
14070            if (v1 != v2) {
14071                return (v1 > v2) ? -1 : 1;
14072            }
14073            if (r1.system != r2.system) {
14074                return r1.system ? -1 : 1;
14075            }
14076            if (r1.activityInfo != null) {
14077                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
14078            }
14079            if (r1.serviceInfo != null) {
14080                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
14081            }
14082            if (r1.providerInfo != null) {
14083                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
14084            }
14085            return 0;
14086        }
14087    };
14088
14089    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
14090            new Comparator<ProviderInfo>() {
14091        public int compare(ProviderInfo p1, ProviderInfo p2) {
14092            final int v1 = p1.initOrder;
14093            final int v2 = p2.initOrder;
14094            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
14095        }
14096    };
14097
14098    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
14099            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
14100            final int[] userIds) {
14101        mHandler.post(new Runnable() {
14102            @Override
14103            public void run() {
14104                try {
14105                    final IActivityManager am = ActivityManager.getService();
14106                    if (am == null) return;
14107                    final int[] resolvedUserIds;
14108                    if (userIds == null) {
14109                        resolvedUserIds = am.getRunningUserIds();
14110                    } else {
14111                        resolvedUserIds = userIds;
14112                    }
14113                    for (int id : resolvedUserIds) {
14114                        final Intent intent = new Intent(action,
14115                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
14116                        if (extras != null) {
14117                            intent.putExtras(extras);
14118                        }
14119                        if (targetPkg != null) {
14120                            intent.setPackage(targetPkg);
14121                        }
14122                        // Modify the UID when posting to other users
14123                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
14124                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
14125                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
14126                            intent.putExtra(Intent.EXTRA_UID, uid);
14127                        }
14128                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
14129                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
14130                        if (DEBUG_BROADCASTS) {
14131                            RuntimeException here = new RuntimeException("here");
14132                            here.fillInStackTrace();
14133                            Slog.d(TAG, "Sending to user " + id + ": "
14134                                    + intent.toShortString(false, true, false, false)
14135                                    + " " + intent.getExtras(), here);
14136                        }
14137                        am.broadcastIntent(null, intent, null, finishedReceiver,
14138                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
14139                                null, finishedReceiver != null, false, id);
14140                    }
14141                } catch (RemoteException ex) {
14142                }
14143            }
14144        });
14145    }
14146
14147    /**
14148     * Check if the external storage media is available. This is true if there
14149     * is a mounted external storage medium or if the external storage is
14150     * emulated.
14151     */
14152    private boolean isExternalMediaAvailable() {
14153        return mMediaMounted || Environment.isExternalStorageEmulated();
14154    }
14155
14156    @Override
14157    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
14158        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14159            return null;
14160        }
14161        // writer
14162        synchronized (mPackages) {
14163            if (!isExternalMediaAvailable()) {
14164                // If the external storage is no longer mounted at this point,
14165                // the caller may not have been able to delete all of this
14166                // packages files and can not delete any more.  Bail.
14167                return null;
14168            }
14169            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
14170            if (lastPackage != null) {
14171                pkgs.remove(lastPackage);
14172            }
14173            if (pkgs.size() > 0) {
14174                return pkgs.get(0);
14175            }
14176        }
14177        return null;
14178    }
14179
14180    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
14181        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
14182                userId, andCode ? 1 : 0, packageName);
14183        if (mSystemReady) {
14184            msg.sendToTarget();
14185        } else {
14186            if (mPostSystemReadyMessages == null) {
14187                mPostSystemReadyMessages = new ArrayList<>();
14188            }
14189            mPostSystemReadyMessages.add(msg);
14190        }
14191    }
14192
14193    void startCleaningPackages() {
14194        // reader
14195        if (!isExternalMediaAvailable()) {
14196            return;
14197        }
14198        synchronized (mPackages) {
14199            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
14200                return;
14201            }
14202        }
14203        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
14204        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
14205        IActivityManager am = ActivityManager.getService();
14206        if (am != null) {
14207            int dcsUid = -1;
14208            synchronized (mPackages) {
14209                if (!mDefaultContainerWhitelisted) {
14210                    mDefaultContainerWhitelisted = true;
14211                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
14212                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
14213                }
14214            }
14215            try {
14216                if (dcsUid > 0) {
14217                    am.backgroundWhitelistUid(dcsUid);
14218                }
14219                am.startService(null, intent, null, false, mContext.getOpPackageName(),
14220                        UserHandle.USER_SYSTEM);
14221            } catch (RemoteException e) {
14222            }
14223        }
14224    }
14225
14226    @Override
14227    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
14228            int installFlags, String installerPackageName, int userId) {
14229        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
14230
14231        final int callingUid = Binder.getCallingUid();
14232        enforceCrossUserPermission(callingUid, userId,
14233                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
14234
14235        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14236            try {
14237                if (observer != null) {
14238                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
14239                }
14240            } catch (RemoteException re) {
14241            }
14242            return;
14243        }
14244
14245        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
14246            installFlags |= PackageManager.INSTALL_FROM_ADB;
14247
14248        } else {
14249            // Caller holds INSTALL_PACKAGES permission, so we're less strict
14250            // about installerPackageName.
14251
14252            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
14253            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
14254        }
14255
14256        UserHandle user;
14257        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
14258            user = UserHandle.ALL;
14259        } else {
14260            user = new UserHandle(userId);
14261        }
14262
14263        // Only system components can circumvent runtime permissions when installing.
14264        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
14265                && mContext.checkCallingOrSelfPermission(Manifest.permission
14266                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
14267            throw new SecurityException("You need the "
14268                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
14269                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
14270        }
14271
14272        if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
14273                || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
14274            throw new IllegalArgumentException(
14275                    "New installs into ASEC containers no longer supported");
14276        }
14277
14278        final File originFile = new File(originPath);
14279        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
14280
14281        final Message msg = mHandler.obtainMessage(INIT_COPY);
14282        final VerificationInfo verificationInfo = new VerificationInfo(
14283                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
14284        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
14285                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
14286                null /*packageAbiOverride*/, null /*grantedPermissions*/,
14287                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
14288        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
14289        msg.obj = params;
14290
14291        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
14292                System.identityHashCode(msg.obj));
14293        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14294                System.identityHashCode(msg.obj));
14295
14296        mHandler.sendMessage(msg);
14297    }
14298
14299
14300    /**
14301     * Ensure that the install reason matches what we know about the package installer (e.g. whether
14302     * it is acting on behalf on an enterprise or the user).
14303     *
14304     * Note that the ordering of the conditionals in this method is important. The checks we perform
14305     * are as follows, in this order:
14306     *
14307     * 1) If the install is being performed by a system app, we can trust the app to have set the
14308     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
14309     *    what it is.
14310     * 2) If the install is being performed by a device or profile owner app, the install reason
14311     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
14312     *    set the install reason correctly. If the app targets an older SDK version where install
14313     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
14314     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
14315     * 3) In all other cases, the install is being performed by a regular app that is neither part
14316     *    of the system nor a device or profile owner. We have no reason to believe that this app is
14317     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
14318     *    set to enterprise policy and if so, change it to unknown instead.
14319     */
14320    private int fixUpInstallReason(String installerPackageName, int installerUid,
14321            int installReason) {
14322        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
14323                == PERMISSION_GRANTED) {
14324            // If the install is being performed by a system app, we trust that app to have set the
14325            // install reason correctly.
14326            return installReason;
14327        }
14328
14329        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
14330            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
14331        if (dpm != null) {
14332            ComponentName owner = null;
14333            try {
14334                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
14335                if (owner == null) {
14336                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
14337                }
14338            } catch (RemoteException e) {
14339            }
14340            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
14341                // If the install is being performed by a device or profile owner, the install
14342                // reason should be enterprise policy.
14343                return PackageManager.INSTALL_REASON_POLICY;
14344            }
14345        }
14346
14347        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
14348            // If the install is being performed by a regular app (i.e. neither system app nor
14349            // device or profile owner), we have no reason to believe that the app is acting on
14350            // behalf of an enterprise. If the app set the install reason to enterprise policy,
14351            // change it to unknown instead.
14352            return PackageManager.INSTALL_REASON_UNKNOWN;
14353        }
14354
14355        // If the install is being performed by a regular app and the install reason was set to any
14356        // value but enterprise policy, leave the install reason unchanged.
14357        return installReason;
14358    }
14359
14360    void installStage(String packageName, File stagedDir, String stagedCid,
14361            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
14362            String installerPackageName, int installerUid, UserHandle user,
14363            Certificate[][] certificates) {
14364        if (DEBUG_EPHEMERAL) {
14365            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14366                Slog.d(TAG, "Ephemeral install of " + packageName);
14367            }
14368        }
14369        final VerificationInfo verificationInfo = new VerificationInfo(
14370                sessionParams.originatingUri, sessionParams.referrerUri,
14371                sessionParams.originatingUid, installerUid);
14372
14373        final OriginInfo origin;
14374        if (stagedDir != null) {
14375            origin = OriginInfo.fromStagedFile(stagedDir);
14376        } else {
14377            origin = OriginInfo.fromStagedContainer(stagedCid);
14378        }
14379
14380        final Message msg = mHandler.obtainMessage(INIT_COPY);
14381        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
14382                sessionParams.installReason);
14383        final InstallParams params = new InstallParams(origin, null, observer,
14384                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
14385                verificationInfo, user, sessionParams.abiOverride,
14386                sessionParams.grantedRuntimePermissions, certificates, installReason);
14387        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
14388        msg.obj = params;
14389
14390        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
14391                System.identityHashCode(msg.obj));
14392        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14393                System.identityHashCode(msg.obj));
14394
14395        mHandler.sendMessage(msg);
14396    }
14397
14398    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
14399            int userId) {
14400        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
14401        sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId);
14402
14403        // Send a session commit broadcast
14404        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
14405        info.installReason = pkgSetting.getInstallReason(userId);
14406        info.appPackageName = packageName;
14407        sendSessionCommitBroadcast(info, userId);
14408    }
14409
14410    public void sendPackageAddedForNewUsers(String packageName, boolean isSystem, int appId, int... userIds) {
14411        if (ArrayUtils.isEmpty(userIds)) {
14412            return;
14413        }
14414        Bundle extras = new Bundle(1);
14415        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
14416        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
14417
14418        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
14419                packageName, extras, 0, null, null, userIds);
14420        if (isSystem) {
14421            mHandler.post(() -> {
14422                        for (int userId : userIds) {
14423                            sendBootCompletedBroadcastToSystemApp(packageName, userId);
14424                        }
14425                    }
14426            );
14427        }
14428    }
14429
14430    /**
14431     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
14432     * automatically without needing an explicit launch.
14433     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
14434     */
14435    private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) {
14436        // If user is not running, the app didn't miss any broadcast
14437        if (!mUserManagerInternal.isUserRunning(userId)) {
14438            return;
14439        }
14440        final IActivityManager am = ActivityManager.getService();
14441        try {
14442            // Deliver LOCKED_BOOT_COMPLETED first
14443            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
14444                    .setPackage(packageName);
14445            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
14446            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
14447                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14448
14449            // Deliver BOOT_COMPLETED only if user is unlocked
14450            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
14451                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
14452                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
14453                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14454            }
14455        } catch (RemoteException e) {
14456            throw e.rethrowFromSystemServer();
14457        }
14458    }
14459
14460    @Override
14461    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
14462            int userId) {
14463        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14464        PackageSetting pkgSetting;
14465        final int callingUid = Binder.getCallingUid();
14466        enforceCrossUserPermission(callingUid, userId,
14467                true /* requireFullPermission */, true /* checkShell */,
14468                "setApplicationHiddenSetting for user " + userId);
14469
14470        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
14471            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
14472            return false;
14473        }
14474
14475        long callingId = Binder.clearCallingIdentity();
14476        try {
14477            boolean sendAdded = false;
14478            boolean sendRemoved = false;
14479            // writer
14480            synchronized (mPackages) {
14481                pkgSetting = mSettings.mPackages.get(packageName);
14482                if (pkgSetting == null) {
14483                    return false;
14484                }
14485                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14486                    return false;
14487                }
14488                // Do not allow "android" is being disabled
14489                if ("android".equals(packageName)) {
14490                    Slog.w(TAG, "Cannot hide package: android");
14491                    return false;
14492                }
14493                // Cannot hide static shared libs as they are considered
14494                // a part of the using app (emulating static linking). Also
14495                // static libs are installed always on internal storage.
14496                PackageParser.Package pkg = mPackages.get(packageName);
14497                if (pkg != null && pkg.staticSharedLibName != null) {
14498                    Slog.w(TAG, "Cannot hide package: " + packageName
14499                            + " providing static shared library: "
14500                            + pkg.staticSharedLibName);
14501                    return false;
14502                }
14503                // Only allow protected packages to hide themselves.
14504                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
14505                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14506                    Slog.w(TAG, "Not hiding protected package: " + packageName);
14507                    return false;
14508                }
14509
14510                if (pkgSetting.getHidden(userId) != hidden) {
14511                    pkgSetting.setHidden(hidden, userId);
14512                    mSettings.writePackageRestrictionsLPr(userId);
14513                    if (hidden) {
14514                        sendRemoved = true;
14515                    } else {
14516                        sendAdded = true;
14517                    }
14518                }
14519            }
14520            if (sendAdded) {
14521                sendPackageAddedForUser(packageName, pkgSetting, userId);
14522                return true;
14523            }
14524            if (sendRemoved) {
14525                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
14526                        "hiding pkg");
14527                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
14528                return true;
14529            }
14530        } finally {
14531            Binder.restoreCallingIdentity(callingId);
14532        }
14533        return false;
14534    }
14535
14536    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
14537            int userId) {
14538        final PackageRemovedInfo info = new PackageRemovedInfo(this);
14539        info.removedPackage = packageName;
14540        info.installerPackageName = pkgSetting.installerPackageName;
14541        info.removedUsers = new int[] {userId};
14542        info.broadcastUsers = new int[] {userId};
14543        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
14544        info.sendPackageRemovedBroadcasts(true /*killApp*/);
14545    }
14546
14547    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
14548        if (pkgList.length > 0) {
14549            Bundle extras = new Bundle(1);
14550            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
14551
14552            sendPackageBroadcast(
14553                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
14554                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
14555                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
14556                    new int[] {userId});
14557        }
14558    }
14559
14560    /**
14561     * Returns true if application is not found or there was an error. Otherwise it returns
14562     * the hidden state of the package for the given user.
14563     */
14564    @Override
14565    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
14566        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14567        final int callingUid = Binder.getCallingUid();
14568        enforceCrossUserPermission(callingUid, userId,
14569                true /* requireFullPermission */, false /* checkShell */,
14570                "getApplicationHidden for user " + userId);
14571        PackageSetting ps;
14572        long callingId = Binder.clearCallingIdentity();
14573        try {
14574            // writer
14575            synchronized (mPackages) {
14576                ps = mSettings.mPackages.get(packageName);
14577                if (ps == null) {
14578                    return true;
14579                }
14580                if (filterAppAccessLPr(ps, callingUid, userId)) {
14581                    return true;
14582                }
14583                return ps.getHidden(userId);
14584            }
14585        } finally {
14586            Binder.restoreCallingIdentity(callingId);
14587        }
14588    }
14589
14590    /**
14591     * @hide
14592     */
14593    @Override
14594    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
14595            int installReason) {
14596        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
14597                null);
14598        PackageSetting pkgSetting;
14599        final int callingUid = Binder.getCallingUid();
14600        enforceCrossUserPermission(callingUid, userId,
14601                true /* requireFullPermission */, true /* checkShell */,
14602                "installExistingPackage for user " + userId);
14603        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14604            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
14605        }
14606
14607        long callingId = Binder.clearCallingIdentity();
14608        try {
14609            boolean installed = false;
14610            final boolean instantApp =
14611                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14612            final boolean fullApp =
14613                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
14614
14615            // writer
14616            synchronized (mPackages) {
14617                pkgSetting = mSettings.mPackages.get(packageName);
14618                if (pkgSetting == null) {
14619                    return PackageManager.INSTALL_FAILED_INVALID_URI;
14620                }
14621                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
14622                    // only allow the existing package to be used if it's installed as a full
14623                    // application for at least one user
14624                    boolean installAllowed = false;
14625                    for (int checkUserId : sUserManager.getUserIds()) {
14626                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
14627                        if (installAllowed) {
14628                            break;
14629                        }
14630                    }
14631                    if (!installAllowed) {
14632                        return PackageManager.INSTALL_FAILED_INVALID_URI;
14633                    }
14634                }
14635                if (!pkgSetting.getInstalled(userId)) {
14636                    pkgSetting.setInstalled(true, userId);
14637                    pkgSetting.setHidden(false, userId);
14638                    pkgSetting.setInstallReason(installReason, userId);
14639                    mSettings.writePackageRestrictionsLPr(userId);
14640                    mSettings.writeKernelMappingLPr(pkgSetting);
14641                    installed = true;
14642                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14643                    // upgrade app from instant to full; we don't allow app downgrade
14644                    installed = true;
14645                }
14646                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
14647            }
14648
14649            if (installed) {
14650                if (pkgSetting.pkg != null) {
14651                    synchronized (mInstallLock) {
14652                        // We don't need to freeze for a brand new install
14653                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
14654                    }
14655                }
14656                sendPackageAddedForUser(packageName, pkgSetting, userId);
14657                synchronized (mPackages) {
14658                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
14659                }
14660            }
14661        } finally {
14662            Binder.restoreCallingIdentity(callingId);
14663        }
14664
14665        return PackageManager.INSTALL_SUCCEEDED;
14666    }
14667
14668    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
14669            boolean instantApp, boolean fullApp) {
14670        // no state specified; do nothing
14671        if (!instantApp && !fullApp) {
14672            return;
14673        }
14674        if (userId != UserHandle.USER_ALL) {
14675            if (instantApp && !pkgSetting.getInstantApp(userId)) {
14676                pkgSetting.setInstantApp(true /*instantApp*/, userId);
14677            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14678                pkgSetting.setInstantApp(false /*instantApp*/, userId);
14679            }
14680        } else {
14681            for (int currentUserId : sUserManager.getUserIds()) {
14682                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
14683                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
14684                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
14685                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
14686                }
14687            }
14688        }
14689    }
14690
14691    boolean isUserRestricted(int userId, String restrictionKey) {
14692        Bundle restrictions = sUserManager.getUserRestrictions(userId);
14693        if (restrictions.getBoolean(restrictionKey, false)) {
14694            Log.w(TAG, "User is restricted: " + restrictionKey);
14695            return true;
14696        }
14697        return false;
14698    }
14699
14700    @Override
14701    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
14702            int userId) {
14703        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14704        final int callingUid = Binder.getCallingUid();
14705        enforceCrossUserPermission(callingUid, userId,
14706                true /* requireFullPermission */, true /* checkShell */,
14707                "setPackagesSuspended for user " + userId);
14708
14709        if (ArrayUtils.isEmpty(packageNames)) {
14710            return packageNames;
14711        }
14712
14713        // List of package names for whom the suspended state has changed.
14714        List<String> changedPackages = new ArrayList<>(packageNames.length);
14715        // List of package names for whom the suspended state is not set as requested in this
14716        // method.
14717        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
14718        long callingId = Binder.clearCallingIdentity();
14719        try {
14720            for (int i = 0; i < packageNames.length; i++) {
14721                String packageName = packageNames[i];
14722                boolean changed = false;
14723                final int appId;
14724                synchronized (mPackages) {
14725                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
14726                    if (pkgSetting == null
14727                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14728                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
14729                                + "\". Skipping suspending/un-suspending.");
14730                        unactionedPackages.add(packageName);
14731                        continue;
14732                    }
14733                    appId = pkgSetting.appId;
14734                    if (pkgSetting.getSuspended(userId) != suspended) {
14735                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
14736                            unactionedPackages.add(packageName);
14737                            continue;
14738                        }
14739                        pkgSetting.setSuspended(suspended, userId);
14740                        mSettings.writePackageRestrictionsLPr(userId);
14741                        changed = true;
14742                        changedPackages.add(packageName);
14743                    }
14744                }
14745
14746                if (changed && suspended) {
14747                    killApplication(packageName, UserHandle.getUid(userId, appId),
14748                            "suspending package");
14749                }
14750            }
14751        } finally {
14752            Binder.restoreCallingIdentity(callingId);
14753        }
14754
14755        if (!changedPackages.isEmpty()) {
14756            sendPackagesSuspendedForUser(changedPackages.toArray(
14757                    new String[changedPackages.size()]), userId, suspended);
14758        }
14759
14760        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
14761    }
14762
14763    @Override
14764    public boolean isPackageSuspendedForUser(String packageName, int userId) {
14765        final int callingUid = Binder.getCallingUid();
14766        enforceCrossUserPermission(callingUid, userId,
14767                true /* requireFullPermission */, false /* checkShell */,
14768                "isPackageSuspendedForUser for user " + userId);
14769        synchronized (mPackages) {
14770            final PackageSetting ps = mSettings.mPackages.get(packageName);
14771            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
14772                throw new IllegalArgumentException("Unknown target package: " + packageName);
14773            }
14774            return ps.getSuspended(userId);
14775        }
14776    }
14777
14778    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
14779        if (isPackageDeviceAdmin(packageName, userId)) {
14780            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14781                    + "\": has an active device admin");
14782            return false;
14783        }
14784
14785        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
14786        if (packageName.equals(activeLauncherPackageName)) {
14787            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14788                    + "\": contains the active launcher");
14789            return false;
14790        }
14791
14792        if (packageName.equals(mRequiredInstallerPackage)) {
14793            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14794                    + "\": required for package installation");
14795            return false;
14796        }
14797
14798        if (packageName.equals(mRequiredUninstallerPackage)) {
14799            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14800                    + "\": required for package uninstallation");
14801            return false;
14802        }
14803
14804        if (packageName.equals(mRequiredVerifierPackage)) {
14805            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14806                    + "\": required for package verification");
14807            return false;
14808        }
14809
14810        if (packageName.equals(getDefaultDialerPackageName(userId))) {
14811            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14812                    + "\": is the default dialer");
14813            return false;
14814        }
14815
14816        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14817            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14818                    + "\": protected package");
14819            return false;
14820        }
14821
14822        // Cannot suspend static shared libs as they are considered
14823        // a part of the using app (emulating static linking). Also
14824        // static libs are installed always on internal storage.
14825        PackageParser.Package pkg = mPackages.get(packageName);
14826        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
14827            Slog.w(TAG, "Cannot suspend package: " + packageName
14828                    + " providing static shared library: "
14829                    + pkg.staticSharedLibName);
14830            return false;
14831        }
14832
14833        return true;
14834    }
14835
14836    private String getActiveLauncherPackageName(int userId) {
14837        Intent intent = new Intent(Intent.ACTION_MAIN);
14838        intent.addCategory(Intent.CATEGORY_HOME);
14839        ResolveInfo resolveInfo = resolveIntent(
14840                intent,
14841                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
14842                PackageManager.MATCH_DEFAULT_ONLY,
14843                userId);
14844
14845        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
14846    }
14847
14848    private String getDefaultDialerPackageName(int userId) {
14849        synchronized (mPackages) {
14850            return mSettings.getDefaultDialerPackageNameLPw(userId);
14851        }
14852    }
14853
14854    @Override
14855    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
14856        mContext.enforceCallingOrSelfPermission(
14857                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14858                "Only package verification agents can verify applications");
14859
14860        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14861        final PackageVerificationResponse response = new PackageVerificationResponse(
14862                verificationCode, Binder.getCallingUid());
14863        msg.arg1 = id;
14864        msg.obj = response;
14865        mHandler.sendMessage(msg);
14866    }
14867
14868    @Override
14869    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
14870            long millisecondsToDelay) {
14871        mContext.enforceCallingOrSelfPermission(
14872                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14873                "Only package verification agents can extend verification timeouts");
14874
14875        final PackageVerificationState state = mPendingVerification.get(id);
14876        final PackageVerificationResponse response = new PackageVerificationResponse(
14877                verificationCodeAtTimeout, Binder.getCallingUid());
14878
14879        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
14880            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
14881        }
14882        if (millisecondsToDelay < 0) {
14883            millisecondsToDelay = 0;
14884        }
14885        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
14886                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
14887            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
14888        }
14889
14890        if ((state != null) && !state.timeoutExtended()) {
14891            state.extendTimeout();
14892
14893            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14894            msg.arg1 = id;
14895            msg.obj = response;
14896            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
14897        }
14898    }
14899
14900    private void broadcastPackageVerified(int verificationId, Uri packageUri,
14901            int verificationCode, UserHandle user) {
14902        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
14903        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
14904        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14905        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14906        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
14907
14908        mContext.sendBroadcastAsUser(intent, user,
14909                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
14910    }
14911
14912    private ComponentName matchComponentForVerifier(String packageName,
14913            List<ResolveInfo> receivers) {
14914        ActivityInfo targetReceiver = null;
14915
14916        final int NR = receivers.size();
14917        for (int i = 0; i < NR; i++) {
14918            final ResolveInfo info = receivers.get(i);
14919            if (info.activityInfo == null) {
14920                continue;
14921            }
14922
14923            if (packageName.equals(info.activityInfo.packageName)) {
14924                targetReceiver = info.activityInfo;
14925                break;
14926            }
14927        }
14928
14929        if (targetReceiver == null) {
14930            return null;
14931        }
14932
14933        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
14934    }
14935
14936    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
14937            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
14938        if (pkgInfo.verifiers.length == 0) {
14939            return null;
14940        }
14941
14942        final int N = pkgInfo.verifiers.length;
14943        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
14944        for (int i = 0; i < N; i++) {
14945            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
14946
14947            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
14948                    receivers);
14949            if (comp == null) {
14950                continue;
14951            }
14952
14953            final int verifierUid = getUidForVerifier(verifierInfo);
14954            if (verifierUid == -1) {
14955                continue;
14956            }
14957
14958            if (DEBUG_VERIFY) {
14959                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
14960                        + " with the correct signature");
14961            }
14962            sufficientVerifiers.add(comp);
14963            verificationState.addSufficientVerifier(verifierUid);
14964        }
14965
14966        return sufficientVerifiers;
14967    }
14968
14969    private int getUidForVerifier(VerifierInfo verifierInfo) {
14970        synchronized (mPackages) {
14971            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
14972            if (pkg == null) {
14973                return -1;
14974            } else if (pkg.mSignatures.length != 1) {
14975                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14976                        + " has more than one signature; ignoring");
14977                return -1;
14978            }
14979
14980            /*
14981             * If the public key of the package's signature does not match
14982             * our expected public key, then this is a different package and
14983             * we should skip.
14984             */
14985
14986            final byte[] expectedPublicKey;
14987            try {
14988                final Signature verifierSig = pkg.mSignatures[0];
14989                final PublicKey publicKey = verifierSig.getPublicKey();
14990                expectedPublicKey = publicKey.getEncoded();
14991            } catch (CertificateException e) {
14992                return -1;
14993            }
14994
14995            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
14996
14997            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
14998                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14999                        + " does not have the expected public key; ignoring");
15000                return -1;
15001            }
15002
15003            return pkg.applicationInfo.uid;
15004        }
15005    }
15006
15007    @Override
15008    public void finishPackageInstall(int token, boolean didLaunch) {
15009        enforceSystemOrRoot("Only the system is allowed to finish installs");
15010
15011        if (DEBUG_INSTALL) {
15012            Slog.v(TAG, "BM finishing package install for " + token);
15013        }
15014        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
15015
15016        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
15017        mHandler.sendMessage(msg);
15018    }
15019
15020    /**
15021     * Get the verification agent timeout.  Used for both the APK verifier and the
15022     * intent filter verifier.
15023     *
15024     * @return verification timeout in milliseconds
15025     */
15026    private long getVerificationTimeout() {
15027        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
15028                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
15029                DEFAULT_VERIFICATION_TIMEOUT);
15030    }
15031
15032    /**
15033     * Get the default verification agent response code.
15034     *
15035     * @return default verification response code
15036     */
15037    private int getDefaultVerificationResponse(UserHandle user) {
15038        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
15039            return PackageManager.VERIFICATION_REJECT;
15040        }
15041        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15042                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
15043                DEFAULT_VERIFICATION_RESPONSE);
15044    }
15045
15046    /**
15047     * Check whether or not package verification has been enabled.
15048     *
15049     * @return true if verification should be performed
15050     */
15051    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
15052        if (!DEFAULT_VERIFY_ENABLE) {
15053            return false;
15054        }
15055
15056        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
15057
15058        // Check if installing from ADB
15059        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
15060            // Do not run verification in a test harness environment
15061            if (ActivityManager.isRunningInTestHarness()) {
15062                return false;
15063            }
15064            if (ensureVerifyAppsEnabled) {
15065                return true;
15066            }
15067            // Check if the developer does not want package verification for ADB installs
15068            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15069                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
15070                return false;
15071            }
15072        } else {
15073            // only when not installed from ADB, skip verification for instant apps when
15074            // the installer and verifier are the same.
15075            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
15076                if (mInstantAppInstallerActivity != null
15077                        && mInstantAppInstallerActivity.packageName.equals(
15078                                mRequiredVerifierPackage)) {
15079                    try {
15080                        mContext.getSystemService(AppOpsManager.class)
15081                                .checkPackage(installerUid, mRequiredVerifierPackage);
15082                        if (DEBUG_VERIFY) {
15083                            Slog.i(TAG, "disable verification for instant app");
15084                        }
15085                        return false;
15086                    } catch (SecurityException ignore) { }
15087                }
15088            }
15089        }
15090
15091        if (ensureVerifyAppsEnabled) {
15092            return true;
15093        }
15094
15095        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15096                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
15097    }
15098
15099    @Override
15100    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
15101            throws RemoteException {
15102        mContext.enforceCallingOrSelfPermission(
15103                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
15104                "Only intentfilter verification agents can verify applications");
15105
15106        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
15107        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
15108                Binder.getCallingUid(), verificationCode, failedDomains);
15109        msg.arg1 = id;
15110        msg.obj = response;
15111        mHandler.sendMessage(msg);
15112    }
15113
15114    @Override
15115    public int getIntentVerificationStatus(String packageName, int userId) {
15116        final int callingUid = Binder.getCallingUid();
15117        if (getInstantAppPackageName(callingUid) != null) {
15118            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
15119        }
15120        synchronized (mPackages) {
15121            final PackageSetting ps = mSettings.mPackages.get(packageName);
15122            if (ps == null
15123                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15124                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
15125            }
15126            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
15127        }
15128    }
15129
15130    @Override
15131    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
15132        mContext.enforceCallingOrSelfPermission(
15133                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15134
15135        boolean result = false;
15136        synchronized (mPackages) {
15137            final PackageSetting ps = mSettings.mPackages.get(packageName);
15138            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15139                return false;
15140            }
15141            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
15142        }
15143        if (result) {
15144            scheduleWritePackageRestrictionsLocked(userId);
15145        }
15146        return result;
15147    }
15148
15149    @Override
15150    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
15151            String packageName) {
15152        final int callingUid = Binder.getCallingUid();
15153        if (getInstantAppPackageName(callingUid) != null) {
15154            return ParceledListSlice.emptyList();
15155        }
15156        synchronized (mPackages) {
15157            final PackageSetting ps = mSettings.mPackages.get(packageName);
15158            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15159                return ParceledListSlice.emptyList();
15160            }
15161            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
15162        }
15163    }
15164
15165    @Override
15166    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
15167        if (TextUtils.isEmpty(packageName)) {
15168            return ParceledListSlice.emptyList();
15169        }
15170        final int callingUid = Binder.getCallingUid();
15171        final int callingUserId = UserHandle.getUserId(callingUid);
15172        synchronized (mPackages) {
15173            PackageParser.Package pkg = mPackages.get(packageName);
15174            if (pkg == null || pkg.activities == null) {
15175                return ParceledListSlice.emptyList();
15176            }
15177            if (pkg.mExtras == null) {
15178                return ParceledListSlice.emptyList();
15179            }
15180            final PackageSetting ps = (PackageSetting) pkg.mExtras;
15181            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
15182                return ParceledListSlice.emptyList();
15183            }
15184            final int count = pkg.activities.size();
15185            ArrayList<IntentFilter> result = new ArrayList<>();
15186            for (int n=0; n<count; n++) {
15187                PackageParser.Activity activity = pkg.activities.get(n);
15188                if (activity.intents != null && activity.intents.size() > 0) {
15189                    result.addAll(activity.intents);
15190                }
15191            }
15192            return new ParceledListSlice<>(result);
15193        }
15194    }
15195
15196    @Override
15197    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
15198        mContext.enforceCallingOrSelfPermission(
15199                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15200
15201        synchronized (mPackages) {
15202            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
15203            if (packageName != null) {
15204                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
15205                        packageName, userId);
15206            }
15207            return result;
15208        }
15209    }
15210
15211    @Override
15212    public String getDefaultBrowserPackageName(int userId) {
15213        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15214            return null;
15215        }
15216        synchronized (mPackages) {
15217            return mSettings.getDefaultBrowserPackageNameLPw(userId);
15218        }
15219    }
15220
15221    /**
15222     * Get the "allow unknown sources" setting.
15223     *
15224     * @return the current "allow unknown sources" setting
15225     */
15226    private int getUnknownSourcesSettings() {
15227        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
15228                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
15229                -1);
15230    }
15231
15232    @Override
15233    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
15234        final int callingUid = Binder.getCallingUid();
15235        if (getInstantAppPackageName(callingUid) != null) {
15236            return;
15237        }
15238        // writer
15239        synchronized (mPackages) {
15240            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
15241            if (targetPackageSetting == null
15242                    || filterAppAccessLPr(
15243                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
15244                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
15245            }
15246
15247            PackageSetting installerPackageSetting;
15248            if (installerPackageName != null) {
15249                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
15250                if (installerPackageSetting == null) {
15251                    throw new IllegalArgumentException("Unknown installer package: "
15252                            + installerPackageName);
15253                }
15254            } else {
15255                installerPackageSetting = null;
15256            }
15257
15258            Signature[] callerSignature;
15259            Object obj = mSettings.getUserIdLPr(callingUid);
15260            if (obj != null) {
15261                if (obj instanceof SharedUserSetting) {
15262                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
15263                } else if (obj instanceof PackageSetting) {
15264                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
15265                } else {
15266                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
15267                }
15268            } else {
15269                throw new SecurityException("Unknown calling UID: " + callingUid);
15270            }
15271
15272            // Verify: can't set installerPackageName to a package that is
15273            // not signed with the same cert as the caller.
15274            if (installerPackageSetting != null) {
15275                if (compareSignatures(callerSignature,
15276                        installerPackageSetting.signatures.mSignatures)
15277                        != PackageManager.SIGNATURE_MATCH) {
15278                    throw new SecurityException(
15279                            "Caller does not have same cert as new installer package "
15280                            + installerPackageName);
15281                }
15282            }
15283
15284            // Verify: if target already has an installer package, it must
15285            // be signed with the same cert as the caller.
15286            if (targetPackageSetting.installerPackageName != null) {
15287                PackageSetting setting = mSettings.mPackages.get(
15288                        targetPackageSetting.installerPackageName);
15289                // If the currently set package isn't valid, then it's always
15290                // okay to change it.
15291                if (setting != null) {
15292                    if (compareSignatures(callerSignature,
15293                            setting.signatures.mSignatures)
15294                            != PackageManager.SIGNATURE_MATCH) {
15295                        throw new SecurityException(
15296                                "Caller does not have same cert as old installer package "
15297                                + targetPackageSetting.installerPackageName);
15298                    }
15299                }
15300            }
15301
15302            // Okay!
15303            targetPackageSetting.installerPackageName = installerPackageName;
15304            if (installerPackageName != null) {
15305                mSettings.mInstallerPackages.add(installerPackageName);
15306            }
15307            scheduleWriteSettingsLocked();
15308        }
15309    }
15310
15311    @Override
15312    public void setApplicationCategoryHint(String packageName, int categoryHint,
15313            String callerPackageName) {
15314        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15315            throw new SecurityException("Instant applications don't have access to this method");
15316        }
15317        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
15318                callerPackageName);
15319        synchronized (mPackages) {
15320            PackageSetting ps = mSettings.mPackages.get(packageName);
15321            if (ps == null) {
15322                throw new IllegalArgumentException("Unknown target package " + packageName);
15323            }
15324            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15325                throw new IllegalArgumentException("Unknown target package " + packageName);
15326            }
15327            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
15328                throw new IllegalArgumentException("Calling package " + callerPackageName
15329                        + " is not installer for " + packageName);
15330            }
15331
15332            if (ps.categoryHint != categoryHint) {
15333                ps.categoryHint = categoryHint;
15334                scheduleWriteSettingsLocked();
15335            }
15336        }
15337    }
15338
15339    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
15340        // Queue up an async operation since the package installation may take a little while.
15341        mHandler.post(new Runnable() {
15342            public void run() {
15343                mHandler.removeCallbacks(this);
15344                 // Result object to be returned
15345                PackageInstalledInfo res = new PackageInstalledInfo();
15346                res.setReturnCode(currentStatus);
15347                res.uid = -1;
15348                res.pkg = null;
15349                res.removedInfo = null;
15350                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15351                    args.doPreInstall(res.returnCode);
15352                    synchronized (mInstallLock) {
15353                        installPackageTracedLI(args, res);
15354                    }
15355                    args.doPostInstall(res.returnCode, res.uid);
15356                }
15357
15358                // A restore should be performed at this point if (a) the install
15359                // succeeded, (b) the operation is not an update, and (c) the new
15360                // package has not opted out of backup participation.
15361                final boolean update = res.removedInfo != null
15362                        && res.removedInfo.removedPackage != null;
15363                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
15364                boolean doRestore = !update
15365                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
15366
15367                // Set up the post-install work request bookkeeping.  This will be used
15368                // and cleaned up by the post-install event handling regardless of whether
15369                // there's a restore pass performed.  Token values are >= 1.
15370                int token;
15371                if (mNextInstallToken < 0) mNextInstallToken = 1;
15372                token = mNextInstallToken++;
15373
15374                PostInstallData data = new PostInstallData(args, res);
15375                mRunningInstalls.put(token, data);
15376                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
15377
15378                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
15379                    // Pass responsibility to the Backup Manager.  It will perform a
15380                    // restore if appropriate, then pass responsibility back to the
15381                    // Package Manager to run the post-install observer callbacks
15382                    // and broadcasts.
15383                    IBackupManager bm = IBackupManager.Stub.asInterface(
15384                            ServiceManager.getService(Context.BACKUP_SERVICE));
15385                    if (bm != null) {
15386                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
15387                                + " to BM for possible restore");
15388                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
15389                        try {
15390                            // TODO: http://b/22388012
15391                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
15392                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
15393                            } else {
15394                                doRestore = false;
15395                            }
15396                        } catch (RemoteException e) {
15397                            // can't happen; the backup manager is local
15398                        } catch (Exception e) {
15399                            Slog.e(TAG, "Exception trying to enqueue restore", e);
15400                            doRestore = false;
15401                        }
15402                    } else {
15403                        Slog.e(TAG, "Backup Manager not found!");
15404                        doRestore = false;
15405                    }
15406                }
15407
15408                if (!doRestore) {
15409                    // No restore possible, or the Backup Manager was mysteriously not
15410                    // available -- just fire the post-install work request directly.
15411                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
15412
15413                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
15414
15415                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
15416                    mHandler.sendMessage(msg);
15417                }
15418            }
15419        });
15420    }
15421
15422    /**
15423     * Callback from PackageSettings whenever an app is first transitioned out of the
15424     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
15425     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
15426     * here whether the app is the target of an ongoing install, and only send the
15427     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
15428     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
15429     * handling.
15430     */
15431    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
15432        // Serialize this with the rest of the install-process message chain.  In the
15433        // restore-at-install case, this Runnable will necessarily run before the
15434        // POST_INSTALL message is processed, so the contents of mRunningInstalls
15435        // are coherent.  In the non-restore case, the app has already completed install
15436        // and been launched through some other means, so it is not in a problematic
15437        // state for observers to see the FIRST_LAUNCH signal.
15438        mHandler.post(new Runnable() {
15439            @Override
15440            public void run() {
15441                for (int i = 0; i < mRunningInstalls.size(); i++) {
15442                    final PostInstallData data = mRunningInstalls.valueAt(i);
15443                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15444                        continue;
15445                    }
15446                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
15447                        // right package; but is it for the right user?
15448                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
15449                            if (userId == data.res.newUsers[uIndex]) {
15450                                if (DEBUG_BACKUP) {
15451                                    Slog.i(TAG, "Package " + pkgName
15452                                            + " being restored so deferring FIRST_LAUNCH");
15453                                }
15454                                return;
15455                            }
15456                        }
15457                    }
15458                }
15459                // didn't find it, so not being restored
15460                if (DEBUG_BACKUP) {
15461                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
15462                }
15463                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
15464            }
15465        });
15466    }
15467
15468    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
15469        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
15470                installerPkg, null, userIds);
15471    }
15472
15473    private abstract class HandlerParams {
15474        private static final int MAX_RETRIES = 4;
15475
15476        /**
15477         * Number of times startCopy() has been attempted and had a non-fatal
15478         * error.
15479         */
15480        private int mRetries = 0;
15481
15482        /** User handle for the user requesting the information or installation. */
15483        private final UserHandle mUser;
15484        String traceMethod;
15485        int traceCookie;
15486
15487        HandlerParams(UserHandle user) {
15488            mUser = user;
15489        }
15490
15491        UserHandle getUser() {
15492            return mUser;
15493        }
15494
15495        HandlerParams setTraceMethod(String traceMethod) {
15496            this.traceMethod = traceMethod;
15497            return this;
15498        }
15499
15500        HandlerParams setTraceCookie(int traceCookie) {
15501            this.traceCookie = traceCookie;
15502            return this;
15503        }
15504
15505        final boolean startCopy() {
15506            boolean res;
15507            try {
15508                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
15509
15510                if (++mRetries > MAX_RETRIES) {
15511                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
15512                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
15513                    handleServiceError();
15514                    return false;
15515                } else {
15516                    handleStartCopy();
15517                    res = true;
15518                }
15519            } catch (RemoteException e) {
15520                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
15521                mHandler.sendEmptyMessage(MCS_RECONNECT);
15522                res = false;
15523            }
15524            handleReturnCode();
15525            return res;
15526        }
15527
15528        final void serviceError() {
15529            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
15530            handleServiceError();
15531            handleReturnCode();
15532        }
15533
15534        abstract void handleStartCopy() throws RemoteException;
15535        abstract void handleServiceError();
15536        abstract void handleReturnCode();
15537    }
15538
15539    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
15540        for (File path : paths) {
15541            try {
15542                mcs.clearDirectory(path.getAbsolutePath());
15543            } catch (RemoteException e) {
15544            }
15545        }
15546    }
15547
15548    static class OriginInfo {
15549        /**
15550         * Location where install is coming from, before it has been
15551         * copied/renamed into place. This could be a single monolithic APK
15552         * file, or a cluster directory. This location may be untrusted.
15553         */
15554        final File file;
15555        final String cid;
15556
15557        /**
15558         * Flag indicating that {@link #file} or {@link #cid} has already been
15559         * staged, meaning downstream users don't need to defensively copy the
15560         * contents.
15561         */
15562        final boolean staged;
15563
15564        /**
15565         * Flag indicating that {@link #file} or {@link #cid} is an already
15566         * installed app that is being moved.
15567         */
15568        final boolean existing;
15569
15570        final String resolvedPath;
15571        final File resolvedFile;
15572
15573        static OriginInfo fromNothing() {
15574            return new OriginInfo(null, null, false, false);
15575        }
15576
15577        static OriginInfo fromUntrustedFile(File file) {
15578            return new OriginInfo(file, null, false, false);
15579        }
15580
15581        static OriginInfo fromExistingFile(File file) {
15582            return new OriginInfo(file, null, false, true);
15583        }
15584
15585        static OriginInfo fromStagedFile(File file) {
15586            return new OriginInfo(file, null, true, false);
15587        }
15588
15589        static OriginInfo fromStagedContainer(String cid) {
15590            return new OriginInfo(null, cid, true, false);
15591        }
15592
15593        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
15594            this.file = file;
15595            this.cid = cid;
15596            this.staged = staged;
15597            this.existing = existing;
15598
15599            if (cid != null) {
15600                resolvedPath = PackageHelper.getSdDir(cid);
15601                resolvedFile = new File(resolvedPath);
15602            } else if (file != null) {
15603                resolvedPath = file.getAbsolutePath();
15604                resolvedFile = file;
15605            } else {
15606                resolvedPath = null;
15607                resolvedFile = null;
15608            }
15609        }
15610    }
15611
15612    static class MoveInfo {
15613        final int moveId;
15614        final String fromUuid;
15615        final String toUuid;
15616        final String packageName;
15617        final String dataAppName;
15618        final int appId;
15619        final String seinfo;
15620        final int targetSdkVersion;
15621
15622        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
15623                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
15624            this.moveId = moveId;
15625            this.fromUuid = fromUuid;
15626            this.toUuid = toUuid;
15627            this.packageName = packageName;
15628            this.dataAppName = dataAppName;
15629            this.appId = appId;
15630            this.seinfo = seinfo;
15631            this.targetSdkVersion = targetSdkVersion;
15632        }
15633    }
15634
15635    static class VerificationInfo {
15636        /** A constant used to indicate that a uid value is not present. */
15637        public static final int NO_UID = -1;
15638
15639        /** URI referencing where the package was downloaded from. */
15640        final Uri originatingUri;
15641
15642        /** HTTP referrer URI associated with the originatingURI. */
15643        final Uri referrer;
15644
15645        /** UID of the application that the install request originated from. */
15646        final int originatingUid;
15647
15648        /** UID of application requesting the install */
15649        final int installerUid;
15650
15651        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
15652            this.originatingUri = originatingUri;
15653            this.referrer = referrer;
15654            this.originatingUid = originatingUid;
15655            this.installerUid = installerUid;
15656        }
15657    }
15658
15659    class InstallParams extends HandlerParams {
15660        final OriginInfo origin;
15661        final MoveInfo move;
15662        final IPackageInstallObserver2 observer;
15663        int installFlags;
15664        final String installerPackageName;
15665        final String volumeUuid;
15666        private InstallArgs mArgs;
15667        private int mRet;
15668        final String packageAbiOverride;
15669        final String[] grantedRuntimePermissions;
15670        final VerificationInfo verificationInfo;
15671        final Certificate[][] certificates;
15672        final int installReason;
15673
15674        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15675                int installFlags, String installerPackageName, String volumeUuid,
15676                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
15677                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
15678            super(user);
15679            this.origin = origin;
15680            this.move = move;
15681            this.observer = observer;
15682            this.installFlags = installFlags;
15683            this.installerPackageName = installerPackageName;
15684            this.volumeUuid = volumeUuid;
15685            this.verificationInfo = verificationInfo;
15686            this.packageAbiOverride = packageAbiOverride;
15687            this.grantedRuntimePermissions = grantedPermissions;
15688            this.certificates = certificates;
15689            this.installReason = installReason;
15690        }
15691
15692        @Override
15693        public String toString() {
15694            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
15695                    + " file=" + origin.file + " cid=" + origin.cid + "}";
15696        }
15697
15698        private int installLocationPolicy(PackageInfoLite pkgLite) {
15699            String packageName = pkgLite.packageName;
15700            int installLocation = pkgLite.installLocation;
15701            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15702            // reader
15703            synchronized (mPackages) {
15704                // Currently installed package which the new package is attempting to replace or
15705                // null if no such package is installed.
15706                PackageParser.Package installedPkg = mPackages.get(packageName);
15707                // Package which currently owns the data which the new package will own if installed.
15708                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
15709                // will be null whereas dataOwnerPkg will contain information about the package
15710                // which was uninstalled while keeping its data.
15711                PackageParser.Package dataOwnerPkg = installedPkg;
15712                if (dataOwnerPkg  == null) {
15713                    PackageSetting ps = mSettings.mPackages.get(packageName);
15714                    if (ps != null) {
15715                        dataOwnerPkg = ps.pkg;
15716                    }
15717                }
15718
15719                if (dataOwnerPkg != null) {
15720                    // If installed, the package will get access to data left on the device by its
15721                    // predecessor. As a security measure, this is permited only if this is not a
15722                    // version downgrade or if the predecessor package is marked as debuggable and
15723                    // a downgrade is explicitly requested.
15724                    //
15725                    // On debuggable platform builds, downgrades are permitted even for
15726                    // non-debuggable packages to make testing easier. Debuggable platform builds do
15727                    // not offer security guarantees and thus it's OK to disable some security
15728                    // mechanisms to make debugging/testing easier on those builds. However, even on
15729                    // debuggable builds downgrades of packages are permitted only if requested via
15730                    // installFlags. This is because we aim to keep the behavior of debuggable
15731                    // platform builds as close as possible to the behavior of non-debuggable
15732                    // platform builds.
15733                    final boolean downgradeRequested =
15734                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
15735                    final boolean packageDebuggable =
15736                                (dataOwnerPkg.applicationInfo.flags
15737                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
15738                    final boolean downgradePermitted =
15739                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
15740                    if (!downgradePermitted) {
15741                        try {
15742                            checkDowngrade(dataOwnerPkg, pkgLite);
15743                        } catch (PackageManagerException e) {
15744                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
15745                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
15746                        }
15747                    }
15748                }
15749
15750                if (installedPkg != null) {
15751                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15752                        // Check for updated system application.
15753                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15754                            if (onSd) {
15755                                Slog.w(TAG, "Cannot install update to system app on sdcard");
15756                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
15757                            }
15758                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15759                        } else {
15760                            if (onSd) {
15761                                // Install flag overrides everything.
15762                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15763                            }
15764                            // If current upgrade specifies particular preference
15765                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
15766                                // Application explicitly specified internal.
15767                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15768                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
15769                                // App explictly prefers external. Let policy decide
15770                            } else {
15771                                // Prefer previous location
15772                                if (isExternal(installedPkg)) {
15773                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15774                                }
15775                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15776                            }
15777                        }
15778                    } else {
15779                        // Invalid install. Return error code
15780                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
15781                    }
15782                }
15783            }
15784            // All the special cases have been taken care of.
15785            // Return result based on recommended install location.
15786            if (onSd) {
15787                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15788            }
15789            return pkgLite.recommendedInstallLocation;
15790        }
15791
15792        /*
15793         * Invoke remote method to get package information and install
15794         * location values. Override install location based on default
15795         * policy if needed and then create install arguments based
15796         * on the install location.
15797         */
15798        public void handleStartCopy() throws RemoteException {
15799            int ret = PackageManager.INSTALL_SUCCEEDED;
15800
15801            // If we're already staged, we've firmly committed to an install location
15802            if (origin.staged) {
15803                if (origin.file != null) {
15804                    installFlags |= PackageManager.INSTALL_INTERNAL;
15805                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15806                } else if (origin.cid != null) {
15807                    installFlags |= PackageManager.INSTALL_EXTERNAL;
15808                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
15809                } else {
15810                    throw new IllegalStateException("Invalid stage location");
15811                }
15812            }
15813
15814            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15815            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
15816            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15817            PackageInfoLite pkgLite = null;
15818
15819            if (onInt && onSd) {
15820                // Check if both bits are set.
15821                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
15822                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15823            } else if (onSd && ephemeral) {
15824                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
15825                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15826            } else {
15827                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
15828                        packageAbiOverride);
15829
15830                if (DEBUG_EPHEMERAL && ephemeral) {
15831                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
15832                }
15833
15834                /*
15835                 * If we have too little free space, try to free cache
15836                 * before giving up.
15837                 */
15838                if (!origin.staged && pkgLite.recommendedInstallLocation
15839                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15840                    // TODO: focus freeing disk space on the target device
15841                    final StorageManager storage = StorageManager.from(mContext);
15842                    final long lowThreshold = storage.getStorageLowBytes(
15843                            Environment.getDataDirectory());
15844
15845                    final long sizeBytes = mContainerService.calculateInstalledSize(
15846                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
15847
15848                    try {
15849                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
15850                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
15851                                installFlags, packageAbiOverride);
15852                    } catch (InstallerException e) {
15853                        Slog.w(TAG, "Failed to free cache", e);
15854                    }
15855
15856                    /*
15857                     * The cache free must have deleted the file we
15858                     * downloaded to install.
15859                     *
15860                     * TODO: fix the "freeCache" call to not delete
15861                     *       the file we care about.
15862                     */
15863                    if (pkgLite.recommendedInstallLocation
15864                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15865                        pkgLite.recommendedInstallLocation
15866                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
15867                    }
15868                }
15869            }
15870
15871            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15872                int loc = pkgLite.recommendedInstallLocation;
15873                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
15874                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15875                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
15876                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
15877                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15878                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15879                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
15880                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
15881                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15882                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
15883                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
15884                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
15885                } else {
15886                    // Override with defaults if needed.
15887                    loc = installLocationPolicy(pkgLite);
15888                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
15889                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
15890                    } else if (!onSd && !onInt) {
15891                        // Override install location with flags
15892                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
15893                            // Set the flag to install on external media.
15894                            installFlags |= PackageManager.INSTALL_EXTERNAL;
15895                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
15896                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
15897                            if (DEBUG_EPHEMERAL) {
15898                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
15899                            }
15900                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
15901                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
15902                                    |PackageManager.INSTALL_INTERNAL);
15903                        } else {
15904                            // Make sure the flag for installing on external
15905                            // media is unset
15906                            installFlags |= PackageManager.INSTALL_INTERNAL;
15907                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15908                        }
15909                    }
15910                }
15911            }
15912
15913            final InstallArgs args = createInstallArgs(this);
15914            mArgs = args;
15915
15916            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15917                // TODO: http://b/22976637
15918                // Apps installed for "all" users use the device owner to verify the app
15919                UserHandle verifierUser = getUser();
15920                if (verifierUser == UserHandle.ALL) {
15921                    verifierUser = UserHandle.SYSTEM;
15922                }
15923
15924                /*
15925                 * Determine if we have any installed package verifiers. If we
15926                 * do, then we'll defer to them to verify the packages.
15927                 */
15928                final int requiredUid = mRequiredVerifierPackage == null ? -1
15929                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15930                                verifierUser.getIdentifier());
15931                final int installerUid =
15932                        verificationInfo == null ? -1 : verificationInfo.installerUid;
15933                if (!origin.existing && requiredUid != -1
15934                        && isVerificationEnabled(
15935                                verifierUser.getIdentifier(), installFlags, installerUid)) {
15936                    final Intent verification = new Intent(
15937                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
15938                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
15939                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
15940                            PACKAGE_MIME_TYPE);
15941                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15942
15943                    // Query all live verifiers based on current user state
15944                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
15945                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
15946
15947                    if (DEBUG_VERIFY) {
15948                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
15949                                + verification.toString() + " with " + pkgLite.verifiers.length
15950                                + " optional verifiers");
15951                    }
15952
15953                    final int verificationId = mPendingVerificationToken++;
15954
15955                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15956
15957                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
15958                            installerPackageName);
15959
15960                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
15961                            installFlags);
15962
15963                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
15964                            pkgLite.packageName);
15965
15966                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
15967                            pkgLite.versionCode);
15968
15969                    if (verificationInfo != null) {
15970                        if (verificationInfo.originatingUri != null) {
15971                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
15972                                    verificationInfo.originatingUri);
15973                        }
15974                        if (verificationInfo.referrer != null) {
15975                            verification.putExtra(Intent.EXTRA_REFERRER,
15976                                    verificationInfo.referrer);
15977                        }
15978                        if (verificationInfo.originatingUid >= 0) {
15979                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
15980                                    verificationInfo.originatingUid);
15981                        }
15982                        if (verificationInfo.installerUid >= 0) {
15983                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
15984                                    verificationInfo.installerUid);
15985                        }
15986                    }
15987
15988                    final PackageVerificationState verificationState = new PackageVerificationState(
15989                            requiredUid, args);
15990
15991                    mPendingVerification.append(verificationId, verificationState);
15992
15993                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
15994                            receivers, verificationState);
15995
15996                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
15997                    final long idleDuration = getVerificationTimeout();
15998
15999                    /*
16000                     * If any sufficient verifiers were listed in the package
16001                     * manifest, attempt to ask them.
16002                     */
16003                    if (sufficientVerifiers != null) {
16004                        final int N = sufficientVerifiers.size();
16005                        if (N == 0) {
16006                            Slog.i(TAG, "Additional verifiers required, but none installed.");
16007                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
16008                        } else {
16009                            for (int i = 0; i < N; i++) {
16010                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
16011                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
16012                                        verifierComponent.getPackageName(), idleDuration,
16013                                        verifierUser.getIdentifier(), false, "package verifier");
16014
16015                                final Intent sufficientIntent = new Intent(verification);
16016                                sufficientIntent.setComponent(verifierComponent);
16017                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
16018                            }
16019                        }
16020                    }
16021
16022                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
16023                            mRequiredVerifierPackage, receivers);
16024                    if (ret == PackageManager.INSTALL_SUCCEEDED
16025                            && mRequiredVerifierPackage != null) {
16026                        Trace.asyncTraceBegin(
16027                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
16028                        /*
16029                         * Send the intent to the required verification agent,
16030                         * but only start the verification timeout after the
16031                         * target BroadcastReceivers have run.
16032                         */
16033                        verification.setComponent(requiredVerifierComponent);
16034                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
16035                                mRequiredVerifierPackage, idleDuration,
16036                                verifierUser.getIdentifier(), false, "package verifier");
16037                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
16038                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
16039                                new BroadcastReceiver() {
16040                                    @Override
16041                                    public void onReceive(Context context, Intent intent) {
16042                                        final Message msg = mHandler
16043                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
16044                                        msg.arg1 = verificationId;
16045                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
16046                                    }
16047                                }, null, 0, null, null);
16048
16049                        /*
16050                         * We don't want the copy to proceed until verification
16051                         * succeeds, so null out this field.
16052                         */
16053                        mArgs = null;
16054                    }
16055                } else {
16056                    /*
16057                     * No package verification is enabled, so immediately start
16058                     * the remote call to initiate copy using temporary file.
16059                     */
16060                    ret = args.copyApk(mContainerService, true);
16061                }
16062            }
16063
16064            mRet = ret;
16065        }
16066
16067        @Override
16068        void handleReturnCode() {
16069            // If mArgs is null, then MCS couldn't be reached. When it
16070            // reconnects, it will try again to install. At that point, this
16071            // will succeed.
16072            if (mArgs != null) {
16073                processPendingInstall(mArgs, mRet);
16074            }
16075        }
16076
16077        @Override
16078        void handleServiceError() {
16079            mArgs = createInstallArgs(this);
16080            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16081        }
16082
16083        public boolean isForwardLocked() {
16084            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16085        }
16086    }
16087
16088    /**
16089     * Used during creation of InstallArgs
16090     *
16091     * @param installFlags package installation flags
16092     * @return true if should be installed on external storage
16093     */
16094    private static boolean installOnExternalAsec(int installFlags) {
16095        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
16096            return false;
16097        }
16098        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
16099            return true;
16100        }
16101        return false;
16102    }
16103
16104    /**
16105     * Used during creation of InstallArgs
16106     *
16107     * @param installFlags package installation flags
16108     * @return true if should be installed as forward locked
16109     */
16110    private static boolean installForwardLocked(int installFlags) {
16111        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16112    }
16113
16114    private InstallArgs createInstallArgs(InstallParams params) {
16115        if (params.move != null) {
16116            return new MoveInstallArgs(params);
16117        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
16118            return new AsecInstallArgs(params);
16119        } else {
16120            return new FileInstallArgs(params);
16121        }
16122    }
16123
16124    /**
16125     * Create args that describe an existing installed package. Typically used
16126     * when cleaning up old installs, or used as a move source.
16127     */
16128    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
16129            String resourcePath, String[] instructionSets) {
16130        final boolean isInAsec;
16131        if (installOnExternalAsec(installFlags)) {
16132            /* Apps on SD card are always in ASEC containers. */
16133            isInAsec = true;
16134        } else if (installForwardLocked(installFlags)
16135                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
16136            /*
16137             * Forward-locked apps are only in ASEC containers if they're the
16138             * new style
16139             */
16140            isInAsec = true;
16141        } else {
16142            isInAsec = false;
16143        }
16144
16145        if (isInAsec) {
16146            return new AsecInstallArgs(codePath, instructionSets,
16147                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
16148        } else {
16149            return new FileInstallArgs(codePath, resourcePath, instructionSets);
16150        }
16151    }
16152
16153    static abstract class InstallArgs {
16154        /** @see InstallParams#origin */
16155        final OriginInfo origin;
16156        /** @see InstallParams#move */
16157        final MoveInfo move;
16158
16159        final IPackageInstallObserver2 observer;
16160        // Always refers to PackageManager flags only
16161        final int installFlags;
16162        final String installerPackageName;
16163        final String volumeUuid;
16164        final UserHandle user;
16165        final String abiOverride;
16166        final String[] installGrantPermissions;
16167        /** If non-null, drop an async trace when the install completes */
16168        final String traceMethod;
16169        final int traceCookie;
16170        final Certificate[][] certificates;
16171        final int installReason;
16172
16173        // The list of instruction sets supported by this app. This is currently
16174        // only used during the rmdex() phase to clean up resources. We can get rid of this
16175        // if we move dex files under the common app path.
16176        /* nullable */ String[] instructionSets;
16177
16178        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
16179                int installFlags, String installerPackageName, String volumeUuid,
16180                UserHandle user, String[] instructionSets,
16181                String abiOverride, String[] installGrantPermissions,
16182                String traceMethod, int traceCookie, Certificate[][] certificates,
16183                int installReason) {
16184            this.origin = origin;
16185            this.move = move;
16186            this.installFlags = installFlags;
16187            this.observer = observer;
16188            this.installerPackageName = installerPackageName;
16189            this.volumeUuid = volumeUuid;
16190            this.user = user;
16191            this.instructionSets = instructionSets;
16192            this.abiOverride = abiOverride;
16193            this.installGrantPermissions = installGrantPermissions;
16194            this.traceMethod = traceMethod;
16195            this.traceCookie = traceCookie;
16196            this.certificates = certificates;
16197            this.installReason = installReason;
16198        }
16199
16200        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
16201        abstract int doPreInstall(int status);
16202
16203        /**
16204         * Rename package into final resting place. All paths on the given
16205         * scanned package should be updated to reflect the rename.
16206         */
16207        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
16208        abstract int doPostInstall(int status, int uid);
16209
16210        /** @see PackageSettingBase#codePathString */
16211        abstract String getCodePath();
16212        /** @see PackageSettingBase#resourcePathString */
16213        abstract String getResourcePath();
16214
16215        // Need installer lock especially for dex file removal.
16216        abstract void cleanUpResourcesLI();
16217        abstract boolean doPostDeleteLI(boolean delete);
16218
16219        /**
16220         * Called before the source arguments are copied. This is used mostly
16221         * for MoveParams when it needs to read the source file to put it in the
16222         * destination.
16223         */
16224        int doPreCopy() {
16225            return PackageManager.INSTALL_SUCCEEDED;
16226        }
16227
16228        /**
16229         * Called after the source arguments are copied. This is used mostly for
16230         * MoveParams when it needs to read the source file to put it in the
16231         * destination.
16232         */
16233        int doPostCopy(int uid) {
16234            return PackageManager.INSTALL_SUCCEEDED;
16235        }
16236
16237        protected boolean isFwdLocked() {
16238            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16239        }
16240
16241        protected boolean isExternalAsec() {
16242            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16243        }
16244
16245        protected boolean isEphemeral() {
16246            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16247        }
16248
16249        UserHandle getUser() {
16250            return user;
16251        }
16252    }
16253
16254    void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
16255        if (!allCodePaths.isEmpty()) {
16256            if (instructionSets == null) {
16257                throw new IllegalStateException("instructionSet == null");
16258            }
16259            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
16260            for (String codePath : allCodePaths) {
16261                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
16262                    try {
16263                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
16264                    } catch (InstallerException ignored) {
16265                    }
16266                }
16267            }
16268        }
16269    }
16270
16271    /**
16272     * Logic to handle installation of non-ASEC applications, including copying
16273     * and renaming logic.
16274     */
16275    class FileInstallArgs extends InstallArgs {
16276        private File codeFile;
16277        private File resourceFile;
16278
16279        // Example topology:
16280        // /data/app/com.example/base.apk
16281        // /data/app/com.example/split_foo.apk
16282        // /data/app/com.example/lib/arm/libfoo.so
16283        // /data/app/com.example/lib/arm64/libfoo.so
16284        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
16285
16286        /** New install */
16287        FileInstallArgs(InstallParams params) {
16288            super(params.origin, params.move, params.observer, params.installFlags,
16289                    params.installerPackageName, params.volumeUuid,
16290                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
16291                    params.grantedRuntimePermissions,
16292                    params.traceMethod, params.traceCookie, params.certificates,
16293                    params.installReason);
16294            if (isFwdLocked()) {
16295                throw new IllegalArgumentException("Forward locking only supported in ASEC");
16296            }
16297        }
16298
16299        /** Existing install */
16300        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
16301            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
16302                    null, null, null, 0, null /*certificates*/,
16303                    PackageManager.INSTALL_REASON_UNKNOWN);
16304            this.codeFile = (codePath != null) ? new File(codePath) : null;
16305            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
16306        }
16307
16308        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16309            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
16310            try {
16311                return doCopyApk(imcs, temp);
16312            } finally {
16313                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16314            }
16315        }
16316
16317        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16318            if (origin.staged) {
16319                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
16320                codeFile = origin.file;
16321                resourceFile = origin.file;
16322                return PackageManager.INSTALL_SUCCEEDED;
16323            }
16324
16325            try {
16326                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16327                final File tempDir =
16328                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
16329                codeFile = tempDir;
16330                resourceFile = tempDir;
16331            } catch (IOException e) {
16332                Slog.w(TAG, "Failed to create copy file: " + e);
16333                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
16334            }
16335
16336            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
16337                @Override
16338                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
16339                    if (!FileUtils.isValidExtFilename(name)) {
16340                        throw new IllegalArgumentException("Invalid filename: " + name);
16341                    }
16342                    try {
16343                        final File file = new File(codeFile, name);
16344                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
16345                                O_RDWR | O_CREAT, 0644);
16346                        Os.chmod(file.getAbsolutePath(), 0644);
16347                        return new ParcelFileDescriptor(fd);
16348                    } catch (ErrnoException e) {
16349                        throw new RemoteException("Failed to open: " + e.getMessage());
16350                    }
16351                }
16352            };
16353
16354            int ret = PackageManager.INSTALL_SUCCEEDED;
16355            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
16356            if (ret != PackageManager.INSTALL_SUCCEEDED) {
16357                Slog.e(TAG, "Failed to copy package");
16358                return ret;
16359            }
16360
16361            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
16362            NativeLibraryHelper.Handle handle = null;
16363            try {
16364                handle = NativeLibraryHelper.Handle.create(codeFile);
16365                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
16366                        abiOverride);
16367            } catch (IOException e) {
16368                Slog.e(TAG, "Copying native libraries failed", e);
16369                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16370            } finally {
16371                IoUtils.closeQuietly(handle);
16372            }
16373
16374            return ret;
16375        }
16376
16377        int doPreInstall(int status) {
16378            if (status != PackageManager.INSTALL_SUCCEEDED) {
16379                cleanUp();
16380            }
16381            return status;
16382        }
16383
16384        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16385            if (status != PackageManager.INSTALL_SUCCEEDED) {
16386                cleanUp();
16387                return false;
16388            }
16389
16390            final File targetDir = codeFile.getParentFile();
16391            final File beforeCodeFile = codeFile;
16392            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
16393
16394            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
16395            try {
16396                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
16397            } catch (ErrnoException e) {
16398                Slog.w(TAG, "Failed to rename", e);
16399                return false;
16400            }
16401
16402            if (!SELinux.restoreconRecursive(afterCodeFile)) {
16403                Slog.w(TAG, "Failed to restorecon");
16404                return false;
16405            }
16406
16407            // Reflect the rename internally
16408            codeFile = afterCodeFile;
16409            resourceFile = afterCodeFile;
16410
16411            // Reflect the rename in scanned details
16412            pkg.setCodePath(afterCodeFile.getAbsolutePath());
16413            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16414                    afterCodeFile, pkg.baseCodePath));
16415            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16416                    afterCodeFile, pkg.splitCodePaths));
16417
16418            // Reflect the rename in app info
16419            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16420            pkg.setApplicationInfoCodePath(pkg.codePath);
16421            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16422            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16423            pkg.setApplicationInfoResourcePath(pkg.codePath);
16424            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16425            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16426
16427            return true;
16428        }
16429
16430        int doPostInstall(int status, int uid) {
16431            if (status != PackageManager.INSTALL_SUCCEEDED) {
16432                cleanUp();
16433            }
16434            return status;
16435        }
16436
16437        @Override
16438        String getCodePath() {
16439            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16440        }
16441
16442        @Override
16443        String getResourcePath() {
16444            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16445        }
16446
16447        private boolean cleanUp() {
16448            if (codeFile == null || !codeFile.exists()) {
16449                return false;
16450            }
16451
16452            removeCodePathLI(codeFile);
16453
16454            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
16455                resourceFile.delete();
16456            }
16457
16458            return true;
16459        }
16460
16461        void cleanUpResourcesLI() {
16462            // Try enumerating all code paths before deleting
16463            List<String> allCodePaths = Collections.EMPTY_LIST;
16464            if (codeFile != null && codeFile.exists()) {
16465                try {
16466                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16467                    allCodePaths = pkg.getAllCodePaths();
16468                } catch (PackageParserException e) {
16469                    // Ignored; we tried our best
16470                }
16471            }
16472
16473            cleanUp();
16474            removeDexFiles(allCodePaths, instructionSets);
16475        }
16476
16477        boolean doPostDeleteLI(boolean delete) {
16478            // XXX err, shouldn't we respect the delete flag?
16479            cleanUpResourcesLI();
16480            return true;
16481        }
16482    }
16483
16484    private boolean isAsecExternal(String cid) {
16485        final String asecPath = PackageHelper.getSdFilesystem(cid);
16486        return !asecPath.startsWith(mAsecInternalPath);
16487    }
16488
16489    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
16490            PackageManagerException {
16491        if (copyRet < 0) {
16492            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
16493                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
16494                throw new PackageManagerException(copyRet, message);
16495            }
16496        }
16497    }
16498
16499    /**
16500     * Extract the StorageManagerService "container ID" from the full code path of an
16501     * .apk.
16502     */
16503    static String cidFromCodePath(String fullCodePath) {
16504        int eidx = fullCodePath.lastIndexOf("/");
16505        String subStr1 = fullCodePath.substring(0, eidx);
16506        int sidx = subStr1.lastIndexOf("/");
16507        return subStr1.substring(sidx+1, eidx);
16508    }
16509
16510    /**
16511     * Logic to handle installation of ASEC applications, including copying and
16512     * renaming logic.
16513     */
16514    class AsecInstallArgs extends InstallArgs {
16515        static final String RES_FILE_NAME = "pkg.apk";
16516        static final String PUBLIC_RES_FILE_NAME = "res.zip";
16517
16518        String cid;
16519        String packagePath;
16520        String resourcePath;
16521
16522        /** New install */
16523        AsecInstallArgs(InstallParams params) {
16524            super(params.origin, params.move, params.observer, params.installFlags,
16525                    params.installerPackageName, params.volumeUuid,
16526                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
16527                    params.grantedRuntimePermissions,
16528                    params.traceMethod, params.traceCookie, params.certificates,
16529                    params.installReason);
16530        }
16531
16532        /** Existing install */
16533        AsecInstallArgs(String fullCodePath, String[] instructionSets,
16534                        boolean isExternal, boolean isForwardLocked) {
16535            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
16536                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
16537                    instructionSets, null, null, null, 0, null /*certificates*/,
16538                    PackageManager.INSTALL_REASON_UNKNOWN);
16539            // Hackily pretend we're still looking at a full code path
16540            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
16541                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
16542            }
16543
16544            // Extract cid from fullCodePath
16545            int eidx = fullCodePath.lastIndexOf("/");
16546            String subStr1 = fullCodePath.substring(0, eidx);
16547            int sidx = subStr1.lastIndexOf("/");
16548            cid = subStr1.substring(sidx+1, eidx);
16549            setMountPath(subStr1);
16550        }
16551
16552        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
16553            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
16554                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
16555                    instructionSets, null, null, null, 0, null /*certificates*/,
16556                    PackageManager.INSTALL_REASON_UNKNOWN);
16557            this.cid = cid;
16558            setMountPath(PackageHelper.getSdDir(cid));
16559        }
16560
16561        void createCopyFile() {
16562            cid = mInstallerService.allocateExternalStageCidLegacy();
16563        }
16564
16565        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16566            if (origin.staged && origin.cid != null) {
16567                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
16568                cid = origin.cid;
16569                setMountPath(PackageHelper.getSdDir(cid));
16570                return PackageManager.INSTALL_SUCCEEDED;
16571            }
16572
16573            if (temp) {
16574                createCopyFile();
16575            } else {
16576                /*
16577                 * Pre-emptively destroy the container since it's destroyed if
16578                 * copying fails due to it existing anyway.
16579                 */
16580                PackageHelper.destroySdDir(cid);
16581            }
16582
16583            final String newMountPath = imcs.copyPackageToContainer(
16584                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
16585                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
16586
16587            if (newMountPath != null) {
16588                setMountPath(newMountPath);
16589                return PackageManager.INSTALL_SUCCEEDED;
16590            } else {
16591                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16592            }
16593        }
16594
16595        @Override
16596        String getCodePath() {
16597            return packagePath;
16598        }
16599
16600        @Override
16601        String getResourcePath() {
16602            return resourcePath;
16603        }
16604
16605        int doPreInstall(int status) {
16606            if (status != PackageManager.INSTALL_SUCCEEDED) {
16607                // Destroy container
16608                PackageHelper.destroySdDir(cid);
16609            } else {
16610                boolean mounted = PackageHelper.isContainerMounted(cid);
16611                if (!mounted) {
16612                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
16613                            Process.SYSTEM_UID);
16614                    if (newMountPath != null) {
16615                        setMountPath(newMountPath);
16616                    } else {
16617                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16618                    }
16619                }
16620            }
16621            return status;
16622        }
16623
16624        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16625            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
16626            String newMountPath = null;
16627            if (PackageHelper.isContainerMounted(cid)) {
16628                // Unmount the container
16629                if (!PackageHelper.unMountSdDir(cid)) {
16630                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
16631                    return false;
16632                }
16633            }
16634            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
16635                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
16636                        " which might be stale. Will try to clean up.");
16637                // Clean up the stale container and proceed to recreate.
16638                if (!PackageHelper.destroySdDir(newCacheId)) {
16639                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
16640                    return false;
16641                }
16642                // Successfully cleaned up stale container. Try to rename again.
16643                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
16644                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
16645                            + " inspite of cleaning it up.");
16646                    return false;
16647                }
16648            }
16649            if (!PackageHelper.isContainerMounted(newCacheId)) {
16650                Slog.w(TAG, "Mounting container " + newCacheId);
16651                newMountPath = PackageHelper.mountSdDir(newCacheId,
16652                        getEncryptKey(), Process.SYSTEM_UID);
16653            } else {
16654                newMountPath = PackageHelper.getSdDir(newCacheId);
16655            }
16656            if (newMountPath == null) {
16657                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
16658                return false;
16659            }
16660            Log.i(TAG, "Succesfully renamed " + cid +
16661                    " to " + newCacheId +
16662                    " at new path: " + newMountPath);
16663            cid = newCacheId;
16664
16665            final File beforeCodeFile = new File(packagePath);
16666            setMountPath(newMountPath);
16667            final File afterCodeFile = new File(packagePath);
16668
16669            // Reflect the rename in scanned details
16670            pkg.setCodePath(afterCodeFile.getAbsolutePath());
16671            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16672                    afterCodeFile, pkg.baseCodePath));
16673            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16674                    afterCodeFile, pkg.splitCodePaths));
16675
16676            // Reflect the rename in app info
16677            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16678            pkg.setApplicationInfoCodePath(pkg.codePath);
16679            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16680            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16681            pkg.setApplicationInfoResourcePath(pkg.codePath);
16682            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16683            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16684
16685            return true;
16686        }
16687
16688        private void setMountPath(String mountPath) {
16689            final File mountFile = new File(mountPath);
16690
16691            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
16692            if (monolithicFile.exists()) {
16693                packagePath = monolithicFile.getAbsolutePath();
16694                if (isFwdLocked()) {
16695                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
16696                } else {
16697                    resourcePath = packagePath;
16698                }
16699            } else {
16700                packagePath = mountFile.getAbsolutePath();
16701                resourcePath = packagePath;
16702            }
16703        }
16704
16705        int doPostInstall(int status, int uid) {
16706            if (status != PackageManager.INSTALL_SUCCEEDED) {
16707                cleanUp();
16708            } else {
16709                final int groupOwner;
16710                final String protectedFile;
16711                if (isFwdLocked()) {
16712                    groupOwner = UserHandle.getSharedAppGid(uid);
16713                    protectedFile = RES_FILE_NAME;
16714                } else {
16715                    groupOwner = -1;
16716                    protectedFile = null;
16717                }
16718
16719                if (uid < Process.FIRST_APPLICATION_UID
16720                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
16721                    Slog.e(TAG, "Failed to finalize " + cid);
16722                    PackageHelper.destroySdDir(cid);
16723                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16724                }
16725
16726                boolean mounted = PackageHelper.isContainerMounted(cid);
16727                if (!mounted) {
16728                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
16729                }
16730            }
16731            return status;
16732        }
16733
16734        private void cleanUp() {
16735            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
16736
16737            // Destroy secure container
16738            PackageHelper.destroySdDir(cid);
16739        }
16740
16741        private List<String> getAllCodePaths() {
16742            final File codeFile = new File(getCodePath());
16743            if (codeFile != null && codeFile.exists()) {
16744                try {
16745                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16746                    return pkg.getAllCodePaths();
16747                } catch (PackageParserException e) {
16748                    // Ignored; we tried our best
16749                }
16750            }
16751            return Collections.EMPTY_LIST;
16752        }
16753
16754        void cleanUpResourcesLI() {
16755            // Enumerate all code paths before deleting
16756            cleanUpResourcesLI(getAllCodePaths());
16757        }
16758
16759        private void cleanUpResourcesLI(List<String> allCodePaths) {
16760            cleanUp();
16761            removeDexFiles(allCodePaths, instructionSets);
16762        }
16763
16764        String getPackageName() {
16765            return getAsecPackageName(cid);
16766        }
16767
16768        boolean doPostDeleteLI(boolean delete) {
16769            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
16770            final List<String> allCodePaths = getAllCodePaths();
16771            boolean mounted = PackageHelper.isContainerMounted(cid);
16772            if (mounted) {
16773                // Unmount first
16774                if (PackageHelper.unMountSdDir(cid)) {
16775                    mounted = false;
16776                }
16777            }
16778            if (!mounted && delete) {
16779                cleanUpResourcesLI(allCodePaths);
16780            }
16781            return !mounted;
16782        }
16783
16784        @Override
16785        int doPreCopy() {
16786            if (isFwdLocked()) {
16787                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
16788                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
16789                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16790                }
16791            }
16792
16793            return PackageManager.INSTALL_SUCCEEDED;
16794        }
16795
16796        @Override
16797        int doPostCopy(int uid) {
16798            if (isFwdLocked()) {
16799                if (uid < Process.FIRST_APPLICATION_UID
16800                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
16801                                RES_FILE_NAME)) {
16802                    Slog.e(TAG, "Failed to finalize " + cid);
16803                    PackageHelper.destroySdDir(cid);
16804                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16805                }
16806            }
16807
16808            return PackageManager.INSTALL_SUCCEEDED;
16809        }
16810    }
16811
16812    /**
16813     * Logic to handle movement of existing installed applications.
16814     */
16815    class MoveInstallArgs extends InstallArgs {
16816        private File codeFile;
16817        private File resourceFile;
16818
16819        /** New install */
16820        MoveInstallArgs(InstallParams params) {
16821            super(params.origin, params.move, params.observer, params.installFlags,
16822                    params.installerPackageName, params.volumeUuid,
16823                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
16824                    params.grantedRuntimePermissions,
16825                    params.traceMethod, params.traceCookie, params.certificates,
16826                    params.installReason);
16827        }
16828
16829        int copyApk(IMediaContainerService imcs, boolean temp) {
16830            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
16831                    + move.fromUuid + " to " + move.toUuid);
16832            synchronized (mInstaller) {
16833                try {
16834                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
16835                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
16836                } catch (InstallerException e) {
16837                    Slog.w(TAG, "Failed to move app", e);
16838                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16839                }
16840            }
16841
16842            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
16843            resourceFile = codeFile;
16844            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
16845
16846            return PackageManager.INSTALL_SUCCEEDED;
16847        }
16848
16849        int doPreInstall(int status) {
16850            if (status != PackageManager.INSTALL_SUCCEEDED) {
16851                cleanUp(move.toUuid);
16852            }
16853            return status;
16854        }
16855
16856        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16857            if (status != PackageManager.INSTALL_SUCCEEDED) {
16858                cleanUp(move.toUuid);
16859                return false;
16860            }
16861
16862            // Reflect the move in app info
16863            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16864            pkg.setApplicationInfoCodePath(pkg.codePath);
16865            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16866            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16867            pkg.setApplicationInfoResourcePath(pkg.codePath);
16868            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16869            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16870
16871            return true;
16872        }
16873
16874        int doPostInstall(int status, int uid) {
16875            if (status == PackageManager.INSTALL_SUCCEEDED) {
16876                cleanUp(move.fromUuid);
16877            } else {
16878                cleanUp(move.toUuid);
16879            }
16880            return status;
16881        }
16882
16883        @Override
16884        String getCodePath() {
16885            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16886        }
16887
16888        @Override
16889        String getResourcePath() {
16890            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16891        }
16892
16893        private boolean cleanUp(String volumeUuid) {
16894            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
16895                    move.dataAppName);
16896            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
16897            final int[] userIds = sUserManager.getUserIds();
16898            synchronized (mInstallLock) {
16899                // Clean up both app data and code
16900                // All package moves are frozen until finished
16901                for (int userId : userIds) {
16902                    try {
16903                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
16904                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
16905                    } catch (InstallerException e) {
16906                        Slog.w(TAG, String.valueOf(e));
16907                    }
16908                }
16909                removeCodePathLI(codeFile);
16910            }
16911            return true;
16912        }
16913
16914        void cleanUpResourcesLI() {
16915            throw new UnsupportedOperationException();
16916        }
16917
16918        boolean doPostDeleteLI(boolean delete) {
16919            throw new UnsupportedOperationException();
16920        }
16921    }
16922
16923    static String getAsecPackageName(String packageCid) {
16924        int idx = packageCid.lastIndexOf("-");
16925        if (idx == -1) {
16926            return packageCid;
16927        }
16928        return packageCid.substring(0, idx);
16929    }
16930
16931    // Utility method used to create code paths based on package name and available index.
16932    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
16933        String idxStr = "";
16934        int idx = 1;
16935        // Fall back to default value of idx=1 if prefix is not
16936        // part of oldCodePath
16937        if (oldCodePath != null) {
16938            String subStr = oldCodePath;
16939            // Drop the suffix right away
16940            if (suffix != null && subStr.endsWith(suffix)) {
16941                subStr = subStr.substring(0, subStr.length() - suffix.length());
16942            }
16943            // If oldCodePath already contains prefix find out the
16944            // ending index to either increment or decrement.
16945            int sidx = subStr.lastIndexOf(prefix);
16946            if (sidx != -1) {
16947                subStr = subStr.substring(sidx + prefix.length());
16948                if (subStr != null) {
16949                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
16950                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
16951                    }
16952                    try {
16953                        idx = Integer.parseInt(subStr);
16954                        if (idx <= 1) {
16955                            idx++;
16956                        } else {
16957                            idx--;
16958                        }
16959                    } catch(NumberFormatException e) {
16960                    }
16961                }
16962            }
16963        }
16964        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
16965        return prefix + idxStr;
16966    }
16967
16968    private File getNextCodePath(File targetDir, String packageName) {
16969        File result;
16970        SecureRandom random = new SecureRandom();
16971        byte[] bytes = new byte[16];
16972        do {
16973            random.nextBytes(bytes);
16974            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
16975            result = new File(targetDir, packageName + "-" + suffix);
16976        } while (result.exists());
16977        return result;
16978    }
16979
16980    // Utility method that returns the relative package path with respect
16981    // to the installation directory. Like say for /data/data/com.test-1.apk
16982    // string com.test-1 is returned.
16983    static String deriveCodePathName(String codePath) {
16984        if (codePath == null) {
16985            return null;
16986        }
16987        final File codeFile = new File(codePath);
16988        final String name = codeFile.getName();
16989        if (codeFile.isDirectory()) {
16990            return name;
16991        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
16992            final int lastDot = name.lastIndexOf('.');
16993            return name.substring(0, lastDot);
16994        } else {
16995            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
16996            return null;
16997        }
16998    }
16999
17000    static class PackageInstalledInfo {
17001        String name;
17002        int uid;
17003        // The set of users that originally had this package installed.
17004        int[] origUsers;
17005        // The set of users that now have this package installed.
17006        int[] newUsers;
17007        PackageParser.Package pkg;
17008        int returnCode;
17009        String returnMsg;
17010        PackageRemovedInfo removedInfo;
17011        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
17012
17013        public void setError(int code, String msg) {
17014            setReturnCode(code);
17015            setReturnMessage(msg);
17016            Slog.w(TAG, msg);
17017        }
17018
17019        public void setError(String msg, PackageParserException e) {
17020            setReturnCode(e.error);
17021            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
17022            Slog.w(TAG, msg, e);
17023        }
17024
17025        public void setError(String msg, PackageManagerException e) {
17026            returnCode = e.error;
17027            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
17028            Slog.w(TAG, msg, e);
17029        }
17030
17031        public void setReturnCode(int returnCode) {
17032            this.returnCode = returnCode;
17033            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17034            for (int i = 0; i < childCount; i++) {
17035                addedChildPackages.valueAt(i).returnCode = returnCode;
17036            }
17037        }
17038
17039        private void setReturnMessage(String returnMsg) {
17040            this.returnMsg = returnMsg;
17041            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17042            for (int i = 0; i < childCount; i++) {
17043                addedChildPackages.valueAt(i).returnMsg = returnMsg;
17044            }
17045        }
17046
17047        // In some error cases we want to convey more info back to the observer
17048        String origPackage;
17049        String origPermission;
17050    }
17051
17052    /*
17053     * Install a non-existing package.
17054     */
17055    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
17056            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
17057            PackageInstalledInfo res, int installReason) {
17058        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
17059
17060        // Remember this for later, in case we need to rollback this install
17061        String pkgName = pkg.packageName;
17062
17063        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
17064
17065        synchronized(mPackages) {
17066            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
17067            if (renamedPackage != null) {
17068                // A package with the same name is already installed, though
17069                // it has been renamed to an older name.  The package we
17070                // are trying to install should be installed as an update to
17071                // the existing one, but that has not been requested, so bail.
17072                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
17073                        + " without first uninstalling package running as "
17074                        + renamedPackage);
17075                return;
17076            }
17077            if (mPackages.containsKey(pkgName)) {
17078                // Don't allow installation over an existing package with the same name.
17079                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
17080                        + " without first uninstalling.");
17081                return;
17082            }
17083        }
17084
17085        try {
17086            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
17087                    System.currentTimeMillis(), user);
17088
17089            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
17090
17091            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17092                prepareAppDataAfterInstallLIF(newPackage);
17093
17094            } else {
17095                // Remove package from internal structures, but keep around any
17096                // data that might have already existed
17097                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
17098                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
17099            }
17100        } catch (PackageManagerException e) {
17101            res.setError("Package couldn't be installed in " + pkg.codePath, e);
17102        }
17103
17104        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17105    }
17106
17107    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
17108        // Can't rotate keys during boot or if sharedUser.
17109        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
17110                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
17111            return false;
17112        }
17113        // app is using upgradeKeySets; make sure all are valid
17114        KeySetManagerService ksms = mSettings.mKeySetManagerService;
17115        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
17116        for (int i = 0; i < upgradeKeySets.length; i++) {
17117            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
17118                Slog.wtf(TAG, "Package "
17119                         + (oldPs.name != null ? oldPs.name : "<null>")
17120                         + " contains upgrade-key-set reference to unknown key-set: "
17121                         + upgradeKeySets[i]
17122                         + " reverting to signatures check.");
17123                return false;
17124            }
17125        }
17126        return true;
17127    }
17128
17129    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
17130        // Upgrade keysets are being used.  Determine if new package has a superset of the
17131        // required keys.
17132        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
17133        KeySetManagerService ksms = mSettings.mKeySetManagerService;
17134        for (int i = 0; i < upgradeKeySets.length; i++) {
17135            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
17136            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
17137                return true;
17138            }
17139        }
17140        return false;
17141    }
17142
17143    private static void updateDigest(MessageDigest digest, File file) throws IOException {
17144        try (DigestInputStream digestStream =
17145                new DigestInputStream(new FileInputStream(file), digest)) {
17146            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
17147        }
17148    }
17149
17150    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
17151            UserHandle user, String installerPackageName, PackageInstalledInfo res,
17152            int installReason) {
17153        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17154
17155        final PackageParser.Package oldPackage;
17156        final PackageSetting ps;
17157        final String pkgName = pkg.packageName;
17158        final int[] allUsers;
17159        final int[] installedUsers;
17160
17161        synchronized(mPackages) {
17162            oldPackage = mPackages.get(pkgName);
17163            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
17164
17165            // don't allow upgrade to target a release SDK from a pre-release SDK
17166            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
17167                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17168            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
17169                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17170            if (oldTargetsPreRelease
17171                    && !newTargetsPreRelease
17172                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
17173                Slog.w(TAG, "Can't install package targeting released sdk");
17174                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
17175                return;
17176            }
17177
17178            ps = mSettings.mPackages.get(pkgName);
17179
17180            // verify signatures are valid
17181            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
17182                if (!checkUpgradeKeySetLP(ps, pkg)) {
17183                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17184                            "New package not signed by keys specified by upgrade-keysets: "
17185                                    + pkgName);
17186                    return;
17187                }
17188            } else {
17189                // default to original signature matching
17190                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
17191                        != PackageManager.SIGNATURE_MATCH) {
17192                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17193                            "New package has a different signature: " + pkgName);
17194                    return;
17195                }
17196            }
17197
17198            // don't allow a system upgrade unless the upgrade hash matches
17199            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
17200                byte[] digestBytes = null;
17201                try {
17202                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
17203                    updateDigest(digest, new File(pkg.baseCodePath));
17204                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
17205                        for (String path : pkg.splitCodePaths) {
17206                            updateDigest(digest, new File(path));
17207                        }
17208                    }
17209                    digestBytes = digest.digest();
17210                } catch (NoSuchAlgorithmException | IOException e) {
17211                    res.setError(INSTALL_FAILED_INVALID_APK,
17212                            "Could not compute hash: " + pkgName);
17213                    return;
17214                }
17215                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
17216                    res.setError(INSTALL_FAILED_INVALID_APK,
17217                            "New package fails restrict-update check: " + pkgName);
17218                    return;
17219                }
17220                // retain upgrade restriction
17221                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
17222            }
17223
17224            // Check for shared user id changes
17225            String invalidPackageName =
17226                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
17227            if (invalidPackageName != null) {
17228                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
17229                        "Package " + invalidPackageName + " tried to change user "
17230                                + oldPackage.mSharedUserId);
17231                return;
17232            }
17233
17234            // In case of rollback, remember per-user/profile install state
17235            allUsers = sUserManager.getUserIds();
17236            installedUsers = ps.queryInstalledUsers(allUsers, true);
17237
17238            // don't allow an upgrade from full to ephemeral
17239            if (isInstantApp) {
17240                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
17241                    for (int currentUser : allUsers) {
17242                        if (!ps.getInstantApp(currentUser)) {
17243                            // can't downgrade from full to instant
17244                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17245                                    + " for user: " + currentUser);
17246                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17247                            return;
17248                        }
17249                    }
17250                } else if (!ps.getInstantApp(user.getIdentifier())) {
17251                    // can't downgrade from full to instant
17252                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17253                            + " for user: " + user.getIdentifier());
17254                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17255                    return;
17256                }
17257            }
17258        }
17259
17260        // Update what is removed
17261        res.removedInfo = new PackageRemovedInfo(this);
17262        res.removedInfo.uid = oldPackage.applicationInfo.uid;
17263        res.removedInfo.removedPackage = oldPackage.packageName;
17264        res.removedInfo.installerPackageName = ps.installerPackageName;
17265        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
17266        res.removedInfo.isUpdate = true;
17267        res.removedInfo.origUsers = installedUsers;
17268        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
17269        for (int i = 0; i < installedUsers.length; i++) {
17270            final int userId = installedUsers[i];
17271            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
17272        }
17273
17274        final int childCount = (oldPackage.childPackages != null)
17275                ? oldPackage.childPackages.size() : 0;
17276        for (int i = 0; i < childCount; i++) {
17277            boolean childPackageUpdated = false;
17278            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
17279            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17280            if (res.addedChildPackages != null) {
17281                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17282                if (childRes != null) {
17283                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
17284                    childRes.removedInfo.removedPackage = childPkg.packageName;
17285                    if (childPs != null) {
17286                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17287                    }
17288                    childRes.removedInfo.isUpdate = true;
17289                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
17290                    childPackageUpdated = true;
17291                }
17292            }
17293            if (!childPackageUpdated) {
17294                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
17295                childRemovedRes.removedPackage = childPkg.packageName;
17296                if (childPs != null) {
17297                    childRemovedRes.installerPackageName = childPs.installerPackageName;
17298                }
17299                childRemovedRes.isUpdate = false;
17300                childRemovedRes.dataRemoved = true;
17301                synchronized (mPackages) {
17302                    if (childPs != null) {
17303                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
17304                    }
17305                }
17306                if (res.removedInfo.removedChildPackages == null) {
17307                    res.removedInfo.removedChildPackages = new ArrayMap<>();
17308                }
17309                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
17310            }
17311        }
17312
17313        boolean sysPkg = (isSystemApp(oldPackage));
17314        if (sysPkg) {
17315            // Set the system/privileged flags as needed
17316            final boolean privileged =
17317                    (oldPackage.applicationInfo.privateFlags
17318                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17319            final int systemPolicyFlags = policyFlags
17320                    | PackageParser.PARSE_IS_SYSTEM
17321                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
17322
17323            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
17324                    user, allUsers, installerPackageName, res, installReason);
17325        } else {
17326            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
17327                    user, allUsers, installerPackageName, res, installReason);
17328        }
17329    }
17330
17331    @Override
17332    public List<String> getPreviousCodePaths(String packageName) {
17333        final int callingUid = Binder.getCallingUid();
17334        final List<String> result = new ArrayList<>();
17335        if (getInstantAppPackageName(callingUid) != null) {
17336            return result;
17337        }
17338        final PackageSetting ps = mSettings.mPackages.get(packageName);
17339        if (ps != null
17340                && ps.oldCodePaths != null
17341                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
17342            result.addAll(ps.oldCodePaths);
17343        }
17344        return result;
17345    }
17346
17347    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
17348            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17349            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17350            int installReason) {
17351        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
17352                + deletedPackage);
17353
17354        String pkgName = deletedPackage.packageName;
17355        boolean deletedPkg = true;
17356        boolean addedPkg = false;
17357        boolean updatedSettings = false;
17358        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
17359        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
17360                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
17361
17362        final long origUpdateTime = (pkg.mExtras != null)
17363                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
17364
17365        // First delete the existing package while retaining the data directory
17366        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17367                res.removedInfo, true, pkg)) {
17368            // If the existing package wasn't successfully deleted
17369            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
17370            deletedPkg = false;
17371        } else {
17372            // Successfully deleted the old package; proceed with replace.
17373
17374            // If deleted package lived in a container, give users a chance to
17375            // relinquish resources before killing.
17376            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
17377                if (DEBUG_INSTALL) {
17378                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
17379                }
17380                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
17381                final ArrayList<String> pkgList = new ArrayList<String>(1);
17382                pkgList.add(deletedPackage.applicationInfo.packageName);
17383                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
17384            }
17385
17386            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17387                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17388            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17389
17390            try {
17391                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
17392                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
17393                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17394                        installReason);
17395
17396                // Update the in-memory copy of the previous code paths.
17397                PackageSetting ps = mSettings.mPackages.get(pkgName);
17398                if (!killApp) {
17399                    if (ps.oldCodePaths == null) {
17400                        ps.oldCodePaths = new ArraySet<>();
17401                    }
17402                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
17403                    if (deletedPackage.splitCodePaths != null) {
17404                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
17405                    }
17406                } else {
17407                    ps.oldCodePaths = null;
17408                }
17409                if (ps.childPackageNames != null) {
17410                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
17411                        final String childPkgName = ps.childPackageNames.get(i);
17412                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
17413                        childPs.oldCodePaths = ps.oldCodePaths;
17414                    }
17415                }
17416                // set instant app status, but, only if it's explicitly specified
17417                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17418                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
17419                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
17420                prepareAppDataAfterInstallLIF(newPackage);
17421                addedPkg = true;
17422                mDexManager.notifyPackageUpdated(newPackage.packageName,
17423                        newPackage.baseCodePath, newPackage.splitCodePaths);
17424            } catch (PackageManagerException e) {
17425                res.setError("Package couldn't be installed in " + pkg.codePath, e);
17426            }
17427        }
17428
17429        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17430            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
17431
17432            // Revert all internal state mutations and added folders for the failed install
17433            if (addedPkg) {
17434                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17435                        res.removedInfo, true, null);
17436            }
17437
17438            // Restore the old package
17439            if (deletedPkg) {
17440                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
17441                File restoreFile = new File(deletedPackage.codePath);
17442                // Parse old package
17443                boolean oldExternal = isExternal(deletedPackage);
17444                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
17445                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
17446                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
17447                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
17448                try {
17449                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
17450                            null);
17451                } catch (PackageManagerException e) {
17452                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
17453                            + e.getMessage());
17454                    return;
17455                }
17456
17457                synchronized (mPackages) {
17458                    // Ensure the installer package name up to date
17459                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17460
17461                    // Update permissions for restored package
17462                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17463
17464                    mSettings.writeLPr();
17465                }
17466
17467                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
17468            }
17469        } else {
17470            synchronized (mPackages) {
17471                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
17472                if (ps != null) {
17473                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
17474                    if (res.removedInfo.removedChildPackages != null) {
17475                        final int childCount = res.removedInfo.removedChildPackages.size();
17476                        // Iterate in reverse as we may modify the collection
17477                        for (int i = childCount - 1; i >= 0; i--) {
17478                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
17479                            if (res.addedChildPackages.containsKey(childPackageName)) {
17480                                res.removedInfo.removedChildPackages.removeAt(i);
17481                            } else {
17482                                PackageRemovedInfo childInfo = res.removedInfo
17483                                        .removedChildPackages.valueAt(i);
17484                                childInfo.removedForAllUsers = mPackages.get(
17485                                        childInfo.removedPackage) == null;
17486                            }
17487                        }
17488                    }
17489                }
17490            }
17491        }
17492    }
17493
17494    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
17495            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17496            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17497            int installReason) {
17498        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
17499                + ", old=" + deletedPackage);
17500
17501        final boolean disabledSystem;
17502
17503        // Remove existing system package
17504        removePackageLI(deletedPackage, true);
17505
17506        synchronized (mPackages) {
17507            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
17508        }
17509        if (!disabledSystem) {
17510            // We didn't need to disable the .apk as a current system package,
17511            // which means we are replacing another update that is already
17512            // installed.  We need to make sure to delete the older one's .apk.
17513            res.removedInfo.args = createInstallArgsForExisting(0,
17514                    deletedPackage.applicationInfo.getCodePath(),
17515                    deletedPackage.applicationInfo.getResourcePath(),
17516                    getAppDexInstructionSets(deletedPackage.applicationInfo));
17517        } else {
17518            res.removedInfo.args = null;
17519        }
17520
17521        // Successfully disabled the old package. Now proceed with re-installation
17522        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17523                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17524        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17525
17526        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17527        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
17528                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
17529
17530        PackageParser.Package newPackage = null;
17531        try {
17532            // Add the package to the internal data structures
17533            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
17534
17535            // Set the update and install times
17536            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
17537            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
17538                    System.currentTimeMillis());
17539
17540            // Update the package dynamic state if succeeded
17541            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17542                // Now that the install succeeded make sure we remove data
17543                // directories for any child package the update removed.
17544                final int deletedChildCount = (deletedPackage.childPackages != null)
17545                        ? deletedPackage.childPackages.size() : 0;
17546                final int newChildCount = (newPackage.childPackages != null)
17547                        ? newPackage.childPackages.size() : 0;
17548                for (int i = 0; i < deletedChildCount; i++) {
17549                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
17550                    boolean childPackageDeleted = true;
17551                    for (int j = 0; j < newChildCount; j++) {
17552                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
17553                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
17554                            childPackageDeleted = false;
17555                            break;
17556                        }
17557                    }
17558                    if (childPackageDeleted) {
17559                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
17560                                deletedChildPkg.packageName);
17561                        if (ps != null && res.removedInfo.removedChildPackages != null) {
17562                            PackageRemovedInfo removedChildRes = res.removedInfo
17563                                    .removedChildPackages.get(deletedChildPkg.packageName);
17564                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
17565                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
17566                        }
17567                    }
17568                }
17569
17570                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17571                        installReason);
17572                prepareAppDataAfterInstallLIF(newPackage);
17573
17574                mDexManager.notifyPackageUpdated(newPackage.packageName,
17575                            newPackage.baseCodePath, newPackage.splitCodePaths);
17576            }
17577        } catch (PackageManagerException e) {
17578            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
17579            res.setError("Package couldn't be installed in " + pkg.codePath, e);
17580        }
17581
17582        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17583            // Re installation failed. Restore old information
17584            // Remove new pkg information
17585            if (newPackage != null) {
17586                removeInstalledPackageLI(newPackage, true);
17587            }
17588            // Add back the old system package
17589            try {
17590                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
17591            } catch (PackageManagerException e) {
17592                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
17593            }
17594
17595            synchronized (mPackages) {
17596                if (disabledSystem) {
17597                    enableSystemPackageLPw(deletedPackage);
17598                }
17599
17600                // Ensure the installer package name up to date
17601                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17602
17603                // Update permissions for restored package
17604                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17605
17606                mSettings.writeLPr();
17607            }
17608
17609            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
17610                    + " after failed upgrade");
17611        }
17612    }
17613
17614    /**
17615     * Checks whether the parent or any of the child packages have a change shared
17616     * user. For a package to be a valid update the shred users of the parent and
17617     * the children should match. We may later support changing child shared users.
17618     * @param oldPkg The updated package.
17619     * @param newPkg The update package.
17620     * @return The shared user that change between the versions.
17621     */
17622    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
17623            PackageParser.Package newPkg) {
17624        // Check parent shared user
17625        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
17626            return newPkg.packageName;
17627        }
17628        // Check child shared users
17629        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
17630        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
17631        for (int i = 0; i < newChildCount; i++) {
17632            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
17633            // If this child was present, did it have the same shared user?
17634            for (int j = 0; j < oldChildCount; j++) {
17635                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
17636                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
17637                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
17638                    return newChildPkg.packageName;
17639                }
17640            }
17641        }
17642        return null;
17643    }
17644
17645    private void removeNativeBinariesLI(PackageSetting ps) {
17646        // Remove the lib path for the parent package
17647        if (ps != null) {
17648            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
17649            // Remove the lib path for the child packages
17650            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
17651            for (int i = 0; i < childCount; i++) {
17652                PackageSetting childPs = null;
17653                synchronized (mPackages) {
17654                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
17655                }
17656                if (childPs != null) {
17657                    NativeLibraryHelper.removeNativeBinariesLI(childPs
17658                            .legacyNativeLibraryPathString);
17659                }
17660            }
17661        }
17662    }
17663
17664    private void enableSystemPackageLPw(PackageParser.Package pkg) {
17665        // Enable the parent package
17666        mSettings.enableSystemPackageLPw(pkg.packageName);
17667        // Enable the child packages
17668        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17669        for (int i = 0; i < childCount; i++) {
17670            PackageParser.Package childPkg = pkg.childPackages.get(i);
17671            mSettings.enableSystemPackageLPw(childPkg.packageName);
17672        }
17673    }
17674
17675    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
17676            PackageParser.Package newPkg) {
17677        // Disable the parent package (parent always replaced)
17678        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
17679        // Disable the child packages
17680        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
17681        for (int i = 0; i < childCount; i++) {
17682            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
17683            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
17684            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
17685        }
17686        return disabled;
17687    }
17688
17689    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
17690            String installerPackageName) {
17691        // Enable the parent package
17692        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
17693        // Enable the child packages
17694        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17695        for (int i = 0; i < childCount; i++) {
17696            PackageParser.Package childPkg = pkg.childPackages.get(i);
17697            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
17698        }
17699    }
17700
17701    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
17702        // Collect all used permissions in the UID
17703        ArraySet<String> usedPermissions = new ArraySet<>();
17704        final int packageCount = su.packages.size();
17705        for (int i = 0; i < packageCount; i++) {
17706            PackageSetting ps = su.packages.valueAt(i);
17707            if (ps.pkg == null) {
17708                continue;
17709            }
17710            final int requestedPermCount = ps.pkg.requestedPermissions.size();
17711            for (int j = 0; j < requestedPermCount; j++) {
17712                String permission = ps.pkg.requestedPermissions.get(j);
17713                BasePermission bp = mSettings.mPermissions.get(permission);
17714                if (bp != null) {
17715                    usedPermissions.add(permission);
17716                }
17717            }
17718        }
17719
17720        PermissionsState permissionsState = su.getPermissionsState();
17721        // Prune install permissions
17722        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
17723        final int installPermCount = installPermStates.size();
17724        for (int i = installPermCount - 1; i >= 0;  i--) {
17725            PermissionState permissionState = installPermStates.get(i);
17726            if (!usedPermissions.contains(permissionState.getName())) {
17727                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
17728                if (bp != null) {
17729                    permissionsState.revokeInstallPermission(bp);
17730                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
17731                            PackageManager.MASK_PERMISSION_FLAGS, 0);
17732                }
17733            }
17734        }
17735
17736        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
17737
17738        // Prune runtime permissions
17739        for (int userId : allUserIds) {
17740            List<PermissionState> runtimePermStates = permissionsState
17741                    .getRuntimePermissionStates(userId);
17742            final int runtimePermCount = runtimePermStates.size();
17743            for (int i = runtimePermCount - 1; i >= 0; i--) {
17744                PermissionState permissionState = runtimePermStates.get(i);
17745                if (!usedPermissions.contains(permissionState.getName())) {
17746                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
17747                    if (bp != null) {
17748                        permissionsState.revokeRuntimePermission(bp, userId);
17749                        permissionsState.updatePermissionFlags(bp, userId,
17750                                PackageManager.MASK_PERMISSION_FLAGS, 0);
17751                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
17752                                runtimePermissionChangedUserIds, userId);
17753                    }
17754                }
17755            }
17756        }
17757
17758        return runtimePermissionChangedUserIds;
17759    }
17760
17761    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
17762            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
17763        // Update the parent package setting
17764        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
17765                res, user, installReason);
17766        // Update the child packages setting
17767        final int childCount = (newPackage.childPackages != null)
17768                ? newPackage.childPackages.size() : 0;
17769        for (int i = 0; i < childCount; i++) {
17770            PackageParser.Package childPackage = newPackage.childPackages.get(i);
17771            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
17772            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
17773                    childRes.origUsers, childRes, user, installReason);
17774        }
17775    }
17776
17777    private void updateSettingsInternalLI(PackageParser.Package newPackage,
17778            String installerPackageName, int[] allUsers, int[] installedForUsers,
17779            PackageInstalledInfo res, UserHandle user, int installReason) {
17780        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
17781
17782        String pkgName = newPackage.packageName;
17783        synchronized (mPackages) {
17784            //write settings. the installStatus will be incomplete at this stage.
17785            //note that the new package setting would have already been
17786            //added to mPackages. It hasn't been persisted yet.
17787            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
17788            // TODO: Remove this write? It's also written at the end of this method
17789            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
17790            mSettings.writeLPr();
17791            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17792        }
17793
17794        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
17795        synchronized (mPackages) {
17796            updatePermissionsLPw(newPackage.packageName, newPackage,
17797                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
17798                            ? UPDATE_PERMISSIONS_ALL : 0));
17799            // For system-bundled packages, we assume that installing an upgraded version
17800            // of the package implies that the user actually wants to run that new code,
17801            // so we enable the package.
17802            PackageSetting ps = mSettings.mPackages.get(pkgName);
17803            final int userId = user.getIdentifier();
17804            if (ps != null) {
17805                if (isSystemApp(newPackage)) {
17806                    if (DEBUG_INSTALL) {
17807                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
17808                    }
17809                    // Enable system package for requested users
17810                    if (res.origUsers != null) {
17811                        for (int origUserId : res.origUsers) {
17812                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
17813                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
17814                                        origUserId, installerPackageName);
17815                            }
17816                        }
17817                    }
17818                    // Also convey the prior install/uninstall state
17819                    if (allUsers != null && installedForUsers != null) {
17820                        for (int currentUserId : allUsers) {
17821                            final boolean installed = ArrayUtils.contains(
17822                                    installedForUsers, currentUserId);
17823                            if (DEBUG_INSTALL) {
17824                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
17825                            }
17826                            ps.setInstalled(installed, currentUserId);
17827                        }
17828                        // these install state changes will be persisted in the
17829                        // upcoming call to mSettings.writeLPr().
17830                    }
17831                }
17832                // It's implied that when a user requests installation, they want the app to be
17833                // installed and enabled.
17834                if (userId != UserHandle.USER_ALL) {
17835                    ps.setInstalled(true, userId);
17836                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
17837                }
17838
17839                // When replacing an existing package, preserve the original install reason for all
17840                // users that had the package installed before.
17841                final Set<Integer> previousUserIds = new ArraySet<>();
17842                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
17843                    final int installReasonCount = res.removedInfo.installReasons.size();
17844                    for (int i = 0; i < installReasonCount; i++) {
17845                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
17846                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
17847                        ps.setInstallReason(previousInstallReason, previousUserId);
17848                        previousUserIds.add(previousUserId);
17849                    }
17850                }
17851
17852                // Set install reason for users that are having the package newly installed.
17853                if (userId == UserHandle.USER_ALL) {
17854                    for (int currentUserId : sUserManager.getUserIds()) {
17855                        if (!previousUserIds.contains(currentUserId)) {
17856                            ps.setInstallReason(installReason, currentUserId);
17857                        }
17858                    }
17859                } else if (!previousUserIds.contains(userId)) {
17860                    ps.setInstallReason(installReason, userId);
17861                }
17862                mSettings.writeKernelMappingLPr(ps);
17863            }
17864            res.name = pkgName;
17865            res.uid = newPackage.applicationInfo.uid;
17866            res.pkg = newPackage;
17867            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
17868            mSettings.setInstallerPackageName(pkgName, installerPackageName);
17869            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17870            //to update install status
17871            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
17872            mSettings.writeLPr();
17873            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17874        }
17875
17876        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17877    }
17878
17879    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
17880        try {
17881            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
17882            installPackageLI(args, res);
17883        } finally {
17884            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17885        }
17886    }
17887
17888    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
17889        final int installFlags = args.installFlags;
17890        final String installerPackageName = args.installerPackageName;
17891        final String volumeUuid = args.volumeUuid;
17892        final File tmpPackageFile = new File(args.getCodePath());
17893        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
17894        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
17895                || (args.volumeUuid != null));
17896        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
17897        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
17898        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
17899        boolean replace = false;
17900        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
17901        if (args.move != null) {
17902            // moving a complete application; perform an initial scan on the new install location
17903            scanFlags |= SCAN_INITIAL;
17904        }
17905        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
17906            scanFlags |= SCAN_DONT_KILL_APP;
17907        }
17908        if (instantApp) {
17909            scanFlags |= SCAN_AS_INSTANT_APP;
17910        }
17911        if (fullApp) {
17912            scanFlags |= SCAN_AS_FULL_APP;
17913        }
17914
17915        // Result object to be returned
17916        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17917
17918        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
17919
17920        // Sanity check
17921        if (instantApp && (forwardLocked || onExternal)) {
17922            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
17923                    + " external=" + onExternal);
17924            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17925            return;
17926        }
17927
17928        // Retrieve PackageSettings and parse package
17929        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
17930                | PackageParser.PARSE_ENFORCE_CODE
17931                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
17932                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
17933                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
17934                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
17935        PackageParser pp = new PackageParser();
17936        pp.setSeparateProcesses(mSeparateProcesses);
17937        pp.setDisplayMetrics(mMetrics);
17938        pp.setCallback(mPackageParserCallback);
17939
17940        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
17941        final PackageParser.Package pkg;
17942        try {
17943            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
17944        } catch (PackageParserException e) {
17945            res.setError("Failed parse during installPackageLI", e);
17946            return;
17947        } finally {
17948            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17949        }
17950
17951        // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
17952        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
17953            Slog.w(TAG, "Instant app package " + pkg.packageName + " does not target O");
17954            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17955                    "Instant app package must target O");
17956            return;
17957        }
17958        if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
17959            Slog.w(TAG, "Instant app package " + pkg.packageName
17960                    + " does not target targetSandboxVersion 2");
17961            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17962                    "Instant app package must use targetSanboxVersion 2");
17963            return;
17964        }
17965
17966        if (pkg.applicationInfo.isStaticSharedLibrary()) {
17967            // Static shared libraries have synthetic package names
17968            renameStaticSharedLibraryPackage(pkg);
17969
17970            // No static shared libs on external storage
17971            if (onExternal) {
17972                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
17973                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17974                        "Packages declaring static-shared libs cannot be updated");
17975                return;
17976            }
17977        }
17978
17979        // If we are installing a clustered package add results for the children
17980        if (pkg.childPackages != null) {
17981            synchronized (mPackages) {
17982                final int childCount = pkg.childPackages.size();
17983                for (int i = 0; i < childCount; i++) {
17984                    PackageParser.Package childPkg = pkg.childPackages.get(i);
17985                    PackageInstalledInfo childRes = new PackageInstalledInfo();
17986                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17987                    childRes.pkg = childPkg;
17988                    childRes.name = childPkg.packageName;
17989                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17990                    if (childPs != null) {
17991                        childRes.origUsers = childPs.queryInstalledUsers(
17992                                sUserManager.getUserIds(), true);
17993                    }
17994                    if ((mPackages.containsKey(childPkg.packageName))) {
17995                        childRes.removedInfo = new PackageRemovedInfo(this);
17996                        childRes.removedInfo.removedPackage = childPkg.packageName;
17997                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17998                    }
17999                    if (res.addedChildPackages == null) {
18000                        res.addedChildPackages = new ArrayMap<>();
18001                    }
18002                    res.addedChildPackages.put(childPkg.packageName, childRes);
18003                }
18004            }
18005        }
18006
18007        // If package doesn't declare API override, mark that we have an install
18008        // time CPU ABI override.
18009        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
18010            pkg.cpuAbiOverride = args.abiOverride;
18011        }
18012
18013        String pkgName = res.name = pkg.packageName;
18014        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
18015            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
18016                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
18017                return;
18018            }
18019        }
18020
18021        try {
18022            // either use what we've been given or parse directly from the APK
18023            if (args.certificates != null) {
18024                try {
18025                    PackageParser.populateCertificates(pkg, args.certificates);
18026                } catch (PackageParserException e) {
18027                    // there was something wrong with the certificates we were given;
18028                    // try to pull them from the APK
18029                    PackageParser.collectCertificates(pkg, parseFlags);
18030                }
18031            } else {
18032                PackageParser.collectCertificates(pkg, parseFlags);
18033            }
18034        } catch (PackageParserException e) {
18035            res.setError("Failed collect during installPackageLI", e);
18036            return;
18037        }
18038
18039        // Get rid of all references to package scan path via parser.
18040        pp = null;
18041        String oldCodePath = null;
18042        boolean systemApp = false;
18043        synchronized (mPackages) {
18044            // Check if installing already existing package
18045            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
18046                String oldName = mSettings.getRenamedPackageLPr(pkgName);
18047                if (pkg.mOriginalPackages != null
18048                        && pkg.mOriginalPackages.contains(oldName)
18049                        && mPackages.containsKey(oldName)) {
18050                    // This package is derived from an original package,
18051                    // and this device has been updating from that original
18052                    // name.  We must continue using the original name, so
18053                    // rename the new package here.
18054                    pkg.setPackageName(oldName);
18055                    pkgName = pkg.packageName;
18056                    replace = true;
18057                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
18058                            + oldName + " pkgName=" + pkgName);
18059                } else if (mPackages.containsKey(pkgName)) {
18060                    // This package, under its official name, already exists
18061                    // on the device; we should replace it.
18062                    replace = true;
18063                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
18064                }
18065
18066                // Child packages are installed through the parent package
18067                if (pkg.parentPackage != null) {
18068                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
18069                            "Package " + pkg.packageName + " is child of package "
18070                                    + pkg.parentPackage.parentPackage + ". Child packages "
18071                                    + "can be updated only through the parent package.");
18072                    return;
18073                }
18074
18075                if (replace) {
18076                    // Prevent apps opting out from runtime permissions
18077                    PackageParser.Package oldPackage = mPackages.get(pkgName);
18078                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
18079                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
18080                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
18081                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
18082                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
18083                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
18084                                        + " doesn't support runtime permissions but the old"
18085                                        + " target SDK " + oldTargetSdk + " does.");
18086                        return;
18087                    }
18088                    // Prevent apps from downgrading their targetSandbox.
18089                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
18090                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
18091                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
18092                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18093                                "Package " + pkg.packageName + " new target sandbox "
18094                                + newTargetSandbox + " is incompatible with the previous value of"
18095                                + oldTargetSandbox + ".");
18096                        return;
18097                    }
18098
18099                    // Prevent installing of child packages
18100                    if (oldPackage.parentPackage != null) {
18101                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
18102                                "Package " + pkg.packageName + " is child of package "
18103                                        + oldPackage.parentPackage + ". Child packages "
18104                                        + "can be updated only through the parent package.");
18105                        return;
18106                    }
18107                }
18108            }
18109
18110            PackageSetting ps = mSettings.mPackages.get(pkgName);
18111            if (ps != null) {
18112                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
18113
18114                // Static shared libs have same package with different versions where
18115                // we internally use a synthetic package name to allow multiple versions
18116                // of the same package, therefore we need to compare signatures against
18117                // the package setting for the latest library version.
18118                PackageSetting signatureCheckPs = ps;
18119                if (pkg.applicationInfo.isStaticSharedLibrary()) {
18120                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
18121                    if (libraryEntry != null) {
18122                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
18123                    }
18124                }
18125
18126                // Quick sanity check that we're signed correctly if updating;
18127                // we'll check this again later when scanning, but we want to
18128                // bail early here before tripping over redefined permissions.
18129                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
18130                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
18131                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
18132                                + pkg.packageName + " upgrade keys do not match the "
18133                                + "previously installed version");
18134                        return;
18135                    }
18136                } else {
18137                    try {
18138                        verifySignaturesLP(signatureCheckPs, pkg);
18139                    } catch (PackageManagerException e) {
18140                        res.setError(e.error, e.getMessage());
18141                        return;
18142                    }
18143                }
18144
18145                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
18146                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
18147                    systemApp = (ps.pkg.applicationInfo.flags &
18148                            ApplicationInfo.FLAG_SYSTEM) != 0;
18149                }
18150                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18151            }
18152
18153            int N = pkg.permissions.size();
18154            for (int i = N-1; i >= 0; i--) {
18155                PackageParser.Permission perm = pkg.permissions.get(i);
18156                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
18157
18158                // Don't allow anyone but the system to define ephemeral permissions.
18159                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_EPHEMERAL) != 0
18160                        && !systemApp) {
18161                    Slog.w(TAG, "Non-System package " + pkg.packageName
18162                            + " attempting to delcare ephemeral permission "
18163                            + perm.info.name + "; Removing ephemeral.");
18164                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_EPHEMERAL;
18165                }
18166                // Check whether the newly-scanned package wants to define an already-defined perm
18167                if (bp != null) {
18168                    // If the defining package is signed with our cert, it's okay.  This
18169                    // also includes the "updating the same package" case, of course.
18170                    // "updating same package" could also involve key-rotation.
18171                    final boolean sigsOk;
18172                    if (bp.sourcePackage.equals(pkg.packageName)
18173                            && (bp.packageSetting instanceof PackageSetting)
18174                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
18175                                    scanFlags))) {
18176                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
18177                    } else {
18178                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
18179                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
18180                    }
18181                    if (!sigsOk) {
18182                        // If the owning package is the system itself, we log but allow
18183                        // install to proceed; we fail the install on all other permission
18184                        // redefinitions.
18185                        if (!bp.sourcePackage.equals("android")) {
18186                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
18187                                    + pkg.packageName + " attempting to redeclare permission "
18188                                    + perm.info.name + " already owned by " + bp.sourcePackage);
18189                            res.origPermission = perm.info.name;
18190                            res.origPackage = bp.sourcePackage;
18191                            return;
18192                        } else {
18193                            Slog.w(TAG, "Package " + pkg.packageName
18194                                    + " attempting to redeclare system permission "
18195                                    + perm.info.name + "; ignoring new declaration");
18196                            pkg.permissions.remove(i);
18197                        }
18198                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
18199                        // Prevent apps to change protection level to dangerous from any other
18200                        // type as this would allow a privilege escalation where an app adds a
18201                        // normal/signature permission in other app's group and later redefines
18202                        // it as dangerous leading to the group auto-grant.
18203                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
18204                                == PermissionInfo.PROTECTION_DANGEROUS) {
18205                            if (bp != null && !bp.isRuntime()) {
18206                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
18207                                        + "non-runtime permission " + perm.info.name
18208                                        + " to runtime; keeping old protection level");
18209                                perm.info.protectionLevel = bp.protectionLevel;
18210                            }
18211                        }
18212                    }
18213                }
18214            }
18215        }
18216
18217        if (systemApp) {
18218            if (onExternal) {
18219                // Abort update; system app can't be replaced with app on sdcard
18220                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
18221                        "Cannot install updates to system apps on sdcard");
18222                return;
18223            } else if (instantApp) {
18224                // Abort update; system app can't be replaced with an instant app
18225                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
18226                        "Cannot update a system app with an instant app");
18227                return;
18228            }
18229        }
18230
18231        if (args.move != null) {
18232            // We did an in-place move, so dex is ready to roll
18233            scanFlags |= SCAN_NO_DEX;
18234            scanFlags |= SCAN_MOVE;
18235
18236            synchronized (mPackages) {
18237                final PackageSetting ps = mSettings.mPackages.get(pkgName);
18238                if (ps == null) {
18239                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
18240                            "Missing settings for moved package " + pkgName);
18241                }
18242
18243                // We moved the entire application as-is, so bring over the
18244                // previously derived ABI information.
18245                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
18246                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
18247            }
18248
18249        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
18250            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
18251            scanFlags |= SCAN_NO_DEX;
18252
18253            try {
18254                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
18255                    args.abiOverride : pkg.cpuAbiOverride);
18256                final boolean extractNativeLibs = !pkg.isLibrary();
18257                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
18258                        extractNativeLibs, mAppLib32InstallDir);
18259            } catch (PackageManagerException pme) {
18260                Slog.e(TAG, "Error deriving application ABI", pme);
18261                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
18262                return;
18263            }
18264
18265            // Shared libraries for the package need to be updated.
18266            synchronized (mPackages) {
18267                try {
18268                    updateSharedLibrariesLPr(pkg, null);
18269                } catch (PackageManagerException e) {
18270                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18271                }
18272            }
18273
18274            // dexopt can take some time to complete, so, for instant apps, we skip this
18275            // step during installation. Instead, we'll take extra time the first time the
18276            // instant app starts. It's preferred to do it this way to provide continuous
18277            // progress to the user instead of mysteriously blocking somewhere in the
18278            // middle of running an instant app. The default behaviour can be overridden
18279            // via gservices.
18280            if (!instantApp || Global.getInt(
18281                        mContext.getContentResolver(), Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0) {
18282                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
18283                // Do not run PackageDexOptimizer through the local performDexOpt
18284                // method because `pkg` may not be in `mPackages` yet.
18285                //
18286                // Also, don't fail application installs if the dexopt step fails.
18287                mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
18288                        null /* instructionSets */, false /* checkProfiles */,
18289                        getCompilerFilterForReason(REASON_INSTALL),
18290                        getOrCreateCompilerPackageStats(pkg),
18291                        mDexManager.isUsedByOtherApps(pkg.packageName),
18292                        true /* bootComplete */,
18293                        false /* downgrade */);
18294                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18295            }
18296
18297            // Notify BackgroundDexOptService that the package has been changed.
18298            // If this is an update of a package which used to fail to compile,
18299            // BDOS will remove it from its blacklist.
18300            // TODO: Layering violation
18301            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
18302        }
18303
18304        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
18305            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
18306            return;
18307        }
18308
18309        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
18310
18311        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
18312                "installPackageLI")) {
18313            if (replace) {
18314                if (pkg.applicationInfo.isStaticSharedLibrary()) {
18315                    // Static libs have a synthetic package name containing the version
18316                    // and cannot be updated as an update would get a new package name,
18317                    // unless this is the exact same version code which is useful for
18318                    // development.
18319                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
18320                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
18321                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
18322                                + "static-shared libs cannot be updated");
18323                        return;
18324                    }
18325                }
18326                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
18327                        installerPackageName, res, args.installReason);
18328            } else {
18329                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
18330                        args.user, installerPackageName, volumeUuid, res, args.installReason);
18331            }
18332        }
18333
18334        synchronized (mPackages) {
18335            final PackageSetting ps = mSettings.mPackages.get(pkgName);
18336            if (ps != null) {
18337                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18338                ps.setUpdateAvailable(false /*updateAvailable*/);
18339            }
18340
18341            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18342            for (int i = 0; i < childCount; i++) {
18343                PackageParser.Package childPkg = pkg.childPackages.get(i);
18344                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
18345                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
18346                if (childPs != null) {
18347                    childRes.newUsers = childPs.queryInstalledUsers(
18348                            sUserManager.getUserIds(), true);
18349                }
18350            }
18351
18352            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
18353                updateSequenceNumberLP(ps, res.newUsers);
18354                updateInstantAppInstallerLocked(pkgName);
18355            }
18356        }
18357    }
18358
18359    private void startIntentFilterVerifications(int userId, boolean replacing,
18360            PackageParser.Package pkg) {
18361        if (mIntentFilterVerifierComponent == null) {
18362            Slog.w(TAG, "No IntentFilter verification will not be done as "
18363                    + "there is no IntentFilterVerifier available!");
18364            return;
18365        }
18366
18367        final int verifierUid = getPackageUid(
18368                mIntentFilterVerifierComponent.getPackageName(),
18369                MATCH_DEBUG_TRIAGED_MISSING,
18370                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
18371
18372        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18373        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
18374        mHandler.sendMessage(msg);
18375
18376        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18377        for (int i = 0; i < childCount; i++) {
18378            PackageParser.Package childPkg = pkg.childPackages.get(i);
18379            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18380            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
18381            mHandler.sendMessage(msg);
18382        }
18383    }
18384
18385    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
18386            PackageParser.Package pkg) {
18387        int size = pkg.activities.size();
18388        if (size == 0) {
18389            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18390                    "No activity, so no need to verify any IntentFilter!");
18391            return;
18392        }
18393
18394        final boolean hasDomainURLs = hasDomainURLs(pkg);
18395        if (!hasDomainURLs) {
18396            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18397                    "No domain URLs, so no need to verify any IntentFilter!");
18398            return;
18399        }
18400
18401        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
18402                + " if any IntentFilter from the " + size
18403                + " Activities needs verification ...");
18404
18405        int count = 0;
18406        final String packageName = pkg.packageName;
18407
18408        synchronized (mPackages) {
18409            // If this is a new install and we see that we've already run verification for this
18410            // package, we have nothing to do: it means the state was restored from backup.
18411            if (!replacing) {
18412                IntentFilterVerificationInfo ivi =
18413                        mSettings.getIntentFilterVerificationLPr(packageName);
18414                if (ivi != null) {
18415                    if (DEBUG_DOMAIN_VERIFICATION) {
18416                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
18417                                + ivi.getStatusString());
18418                    }
18419                    return;
18420                }
18421            }
18422
18423            // If any filters need to be verified, then all need to be.
18424            boolean needToVerify = false;
18425            for (PackageParser.Activity a : pkg.activities) {
18426                for (ActivityIntentInfo filter : a.intents) {
18427                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
18428                        if (DEBUG_DOMAIN_VERIFICATION) {
18429                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
18430                        }
18431                        needToVerify = true;
18432                        break;
18433                    }
18434                }
18435            }
18436
18437            if (needToVerify) {
18438                final int verificationId = mIntentFilterVerificationToken++;
18439                for (PackageParser.Activity a : pkg.activities) {
18440                    for (ActivityIntentInfo filter : a.intents) {
18441                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
18442                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18443                                    "Verification needed for IntentFilter:" + filter.toString());
18444                            mIntentFilterVerifier.addOneIntentFilterVerification(
18445                                    verifierUid, userId, verificationId, filter, packageName);
18446                            count++;
18447                        }
18448                    }
18449                }
18450            }
18451        }
18452
18453        if (count > 0) {
18454            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
18455                    + " IntentFilter verification" + (count > 1 ? "s" : "")
18456                    +  " for userId:" + userId);
18457            mIntentFilterVerifier.startVerifications(userId);
18458        } else {
18459            if (DEBUG_DOMAIN_VERIFICATION) {
18460                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
18461            }
18462        }
18463    }
18464
18465    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
18466        final ComponentName cn  = filter.activity.getComponentName();
18467        final String packageName = cn.getPackageName();
18468
18469        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
18470                packageName);
18471        if (ivi == null) {
18472            return true;
18473        }
18474        int status = ivi.getStatus();
18475        switch (status) {
18476            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
18477            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
18478                return true;
18479
18480            default:
18481                // Nothing to do
18482                return false;
18483        }
18484    }
18485
18486    private static boolean isMultiArch(ApplicationInfo info) {
18487        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
18488    }
18489
18490    private static boolean isExternal(PackageParser.Package pkg) {
18491        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18492    }
18493
18494    private static boolean isExternal(PackageSetting ps) {
18495        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18496    }
18497
18498    private static boolean isSystemApp(PackageParser.Package pkg) {
18499        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
18500    }
18501
18502    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
18503        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
18504    }
18505
18506    private static boolean hasDomainURLs(PackageParser.Package pkg) {
18507        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
18508    }
18509
18510    private static boolean isSystemApp(PackageSetting ps) {
18511        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
18512    }
18513
18514    private static boolean isUpdatedSystemApp(PackageSetting ps) {
18515        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
18516    }
18517
18518    private int packageFlagsToInstallFlags(PackageSetting ps) {
18519        int installFlags = 0;
18520        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
18521            // This existing package was an external ASEC install when we have
18522            // the external flag without a UUID
18523            installFlags |= PackageManager.INSTALL_EXTERNAL;
18524        }
18525        if (ps.isForwardLocked()) {
18526            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
18527        }
18528        return installFlags;
18529    }
18530
18531    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
18532        if (isExternal(pkg)) {
18533            if (TextUtils.isEmpty(pkg.volumeUuid)) {
18534                return StorageManager.UUID_PRIMARY_PHYSICAL;
18535            } else {
18536                return pkg.volumeUuid;
18537            }
18538        } else {
18539            return StorageManager.UUID_PRIVATE_INTERNAL;
18540        }
18541    }
18542
18543    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
18544        if (isExternal(pkg)) {
18545            if (TextUtils.isEmpty(pkg.volumeUuid)) {
18546                return mSettings.getExternalVersion();
18547            } else {
18548                return mSettings.findOrCreateVersion(pkg.volumeUuid);
18549            }
18550        } else {
18551            return mSettings.getInternalVersion();
18552        }
18553    }
18554
18555    private void deleteTempPackageFiles() {
18556        final FilenameFilter filter = new FilenameFilter() {
18557            public boolean accept(File dir, String name) {
18558                return name.startsWith("vmdl") && name.endsWith(".tmp");
18559            }
18560        };
18561        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
18562            file.delete();
18563        }
18564    }
18565
18566    @Override
18567    public void deletePackageAsUser(String packageName, int versionCode,
18568            IPackageDeleteObserver observer, int userId, int flags) {
18569        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
18570                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
18571    }
18572
18573    @Override
18574    public void deletePackageVersioned(VersionedPackage versionedPackage,
18575            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
18576        final int callingUid = Binder.getCallingUid();
18577        mContext.enforceCallingOrSelfPermission(
18578                android.Manifest.permission.DELETE_PACKAGES, null);
18579        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
18580        Preconditions.checkNotNull(versionedPackage);
18581        Preconditions.checkNotNull(observer);
18582        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
18583                PackageManager.VERSION_CODE_HIGHEST,
18584                Integer.MAX_VALUE, "versionCode must be >= -1");
18585
18586        final String packageName = versionedPackage.getPackageName();
18587        final int versionCode = versionedPackage.getVersionCode();
18588        final String internalPackageName;
18589        synchronized (mPackages) {
18590            // Normalize package name to handle renamed packages and static libs
18591            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
18592                    versionedPackage.getVersionCode());
18593        }
18594
18595        final int uid = Binder.getCallingUid();
18596        if (!isOrphaned(internalPackageName)
18597                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
18598            try {
18599                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
18600                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
18601                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
18602                observer.onUserActionRequired(intent);
18603            } catch (RemoteException re) {
18604            }
18605            return;
18606        }
18607        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
18608        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
18609        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
18610            mContext.enforceCallingOrSelfPermission(
18611                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
18612                    "deletePackage for user " + userId);
18613        }
18614
18615        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
18616            try {
18617                observer.onPackageDeleted(packageName,
18618                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
18619            } catch (RemoteException re) {
18620            }
18621            return;
18622        }
18623
18624        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
18625            try {
18626                observer.onPackageDeleted(packageName,
18627                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
18628            } catch (RemoteException re) {
18629            }
18630            return;
18631        }
18632
18633        if (DEBUG_REMOVE) {
18634            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
18635                    + " deleteAllUsers: " + deleteAllUsers + " version="
18636                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
18637                    ? "VERSION_CODE_HIGHEST" : versionCode));
18638        }
18639        // Queue up an async operation since the package deletion may take a little while.
18640        mHandler.post(new Runnable() {
18641            public void run() {
18642                mHandler.removeCallbacks(this);
18643                int returnCode;
18644                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
18645                boolean doDeletePackage = true;
18646                if (ps != null) {
18647                    final boolean targetIsInstantApp =
18648                            ps.getInstantApp(UserHandle.getUserId(callingUid));
18649                    doDeletePackage = !targetIsInstantApp
18650                            || canViewInstantApps;
18651                }
18652                if (doDeletePackage) {
18653                    if (!deleteAllUsers) {
18654                        returnCode = deletePackageX(internalPackageName, versionCode,
18655                                userId, deleteFlags);
18656                    } else {
18657                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
18658                                internalPackageName, users);
18659                        // If nobody is blocking uninstall, proceed with delete for all users
18660                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
18661                            returnCode = deletePackageX(internalPackageName, versionCode,
18662                                    userId, deleteFlags);
18663                        } else {
18664                            // Otherwise uninstall individually for users with blockUninstalls=false
18665                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
18666                            for (int userId : users) {
18667                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
18668                                    returnCode = deletePackageX(internalPackageName, versionCode,
18669                                            userId, userFlags);
18670                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
18671                                        Slog.w(TAG, "Package delete failed for user " + userId
18672                                                + ", returnCode " + returnCode);
18673                                    }
18674                                }
18675                            }
18676                            // The app has only been marked uninstalled for certain users.
18677                            // We still need to report that delete was blocked
18678                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
18679                        }
18680                    }
18681                } else {
18682                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18683                }
18684                try {
18685                    observer.onPackageDeleted(packageName, returnCode, null);
18686                } catch (RemoteException e) {
18687                    Log.i(TAG, "Observer no longer exists.");
18688                } //end catch
18689            } //end run
18690        });
18691    }
18692
18693    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
18694        if (pkg.staticSharedLibName != null) {
18695            return pkg.manifestPackageName;
18696        }
18697        return pkg.packageName;
18698    }
18699
18700    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
18701        // Handle renamed packages
18702        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
18703        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
18704
18705        // Is this a static library?
18706        SparseArray<SharedLibraryEntry> versionedLib =
18707                mStaticLibsByDeclaringPackage.get(packageName);
18708        if (versionedLib == null || versionedLib.size() <= 0) {
18709            return packageName;
18710        }
18711
18712        // Figure out which lib versions the caller can see
18713        SparseIntArray versionsCallerCanSee = null;
18714        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
18715        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
18716                && callingAppId != Process.ROOT_UID) {
18717            versionsCallerCanSee = new SparseIntArray();
18718            String libName = versionedLib.valueAt(0).info.getName();
18719            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
18720            if (uidPackages != null) {
18721                for (String uidPackage : uidPackages) {
18722                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
18723                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
18724                    if (libIdx >= 0) {
18725                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
18726                        versionsCallerCanSee.append(libVersion, libVersion);
18727                    }
18728                }
18729            }
18730        }
18731
18732        // Caller can see nothing - done
18733        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
18734            return packageName;
18735        }
18736
18737        // Find the version the caller can see and the app version code
18738        SharedLibraryEntry highestVersion = null;
18739        final int versionCount = versionedLib.size();
18740        for (int i = 0; i < versionCount; i++) {
18741            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
18742            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
18743                    libEntry.info.getVersion()) < 0) {
18744                continue;
18745            }
18746            final int libVersionCode = libEntry.info.getDeclaringPackage().getVersionCode();
18747            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
18748                if (libVersionCode == versionCode) {
18749                    return libEntry.apk;
18750                }
18751            } else if (highestVersion == null) {
18752                highestVersion = libEntry;
18753            } else if (libVersionCode  > highestVersion.info
18754                    .getDeclaringPackage().getVersionCode()) {
18755                highestVersion = libEntry;
18756            }
18757        }
18758
18759        if (highestVersion != null) {
18760            return highestVersion.apk;
18761        }
18762
18763        return packageName;
18764    }
18765
18766    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
18767        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
18768              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
18769            return true;
18770        }
18771        final int callingUserId = UserHandle.getUserId(callingUid);
18772        // If the caller installed the pkgName, then allow it to silently uninstall.
18773        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
18774            return true;
18775        }
18776
18777        // Allow package verifier to silently uninstall.
18778        if (mRequiredVerifierPackage != null &&
18779                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
18780            return true;
18781        }
18782
18783        // Allow package uninstaller to silently uninstall.
18784        if (mRequiredUninstallerPackage != null &&
18785                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
18786            return true;
18787        }
18788
18789        // Allow storage manager to silently uninstall.
18790        if (mStorageManagerPackage != null &&
18791                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
18792            return true;
18793        }
18794
18795        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
18796        // uninstall for device owner provisioning.
18797        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
18798                == PERMISSION_GRANTED) {
18799            return true;
18800        }
18801
18802        return false;
18803    }
18804
18805    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
18806        int[] result = EMPTY_INT_ARRAY;
18807        for (int userId : userIds) {
18808            if (getBlockUninstallForUser(packageName, userId)) {
18809                result = ArrayUtils.appendInt(result, userId);
18810            }
18811        }
18812        return result;
18813    }
18814
18815    @Override
18816    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
18817        final int callingUid = Binder.getCallingUid();
18818        if (getInstantAppPackageName(callingUid) != null
18819                && !isCallerSameApp(packageName, callingUid)) {
18820            return false;
18821        }
18822        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
18823    }
18824
18825    private boolean isPackageDeviceAdmin(String packageName, int userId) {
18826        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
18827                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
18828        try {
18829            if (dpm != null) {
18830                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
18831                        /* callingUserOnly =*/ false);
18832                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
18833                        : deviceOwnerComponentName.getPackageName();
18834                // Does the package contains the device owner?
18835                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
18836                // this check is probably not needed, since DO should be registered as a device
18837                // admin on some user too. (Original bug for this: b/17657954)
18838                if (packageName.equals(deviceOwnerPackageName)) {
18839                    return true;
18840                }
18841                // Does it contain a device admin for any user?
18842                int[] users;
18843                if (userId == UserHandle.USER_ALL) {
18844                    users = sUserManager.getUserIds();
18845                } else {
18846                    users = new int[]{userId};
18847                }
18848                for (int i = 0; i < users.length; ++i) {
18849                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
18850                        return true;
18851                    }
18852                }
18853            }
18854        } catch (RemoteException e) {
18855        }
18856        return false;
18857    }
18858
18859    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
18860        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
18861    }
18862
18863    /**
18864     *  This method is an internal method that could be get invoked either
18865     *  to delete an installed package or to clean up a failed installation.
18866     *  After deleting an installed package, a broadcast is sent to notify any
18867     *  listeners that the package has been removed. For cleaning up a failed
18868     *  installation, the broadcast is not necessary since the package's
18869     *  installation wouldn't have sent the initial broadcast either
18870     *  The key steps in deleting a package are
18871     *  deleting the package information in internal structures like mPackages,
18872     *  deleting the packages base directories through installd
18873     *  updating mSettings to reflect current status
18874     *  persisting settings for later use
18875     *  sending a broadcast if necessary
18876     */
18877    int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
18878        final PackageRemovedInfo info = new PackageRemovedInfo(this);
18879        final boolean res;
18880
18881        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
18882                ? UserHandle.USER_ALL : userId;
18883
18884        if (isPackageDeviceAdmin(packageName, removeUser)) {
18885            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
18886            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
18887        }
18888
18889        PackageSetting uninstalledPs = null;
18890        PackageParser.Package pkg = null;
18891
18892        // for the uninstall-updates case and restricted profiles, remember the per-
18893        // user handle installed state
18894        int[] allUsers;
18895        synchronized (mPackages) {
18896            uninstalledPs = mSettings.mPackages.get(packageName);
18897            if (uninstalledPs == null) {
18898                Slog.w(TAG, "Not removing non-existent package " + packageName);
18899                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18900            }
18901
18902            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
18903                    && uninstalledPs.versionCode != versionCode) {
18904                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
18905                        + uninstalledPs.versionCode + " != " + versionCode);
18906                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18907            }
18908
18909            // Static shared libs can be declared by any package, so let us not
18910            // allow removing a package if it provides a lib others depend on.
18911            pkg = mPackages.get(packageName);
18912
18913            allUsers = sUserManager.getUserIds();
18914
18915            if (pkg != null && pkg.staticSharedLibName != null) {
18916                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
18917                        pkg.staticSharedLibVersion);
18918                if (libEntry != null) {
18919                    for (int currUserId : allUsers) {
18920                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
18921                            continue;
18922                        }
18923                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
18924                                libEntry.info, 0, currUserId);
18925                        if (!ArrayUtils.isEmpty(libClientPackages)) {
18926                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
18927                                    + " hosting lib " + libEntry.info.getName() + " version "
18928                                    + libEntry.info.getVersion() + " used by " + libClientPackages
18929                                    + " for user " + currUserId);
18930                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
18931                        }
18932                    }
18933                }
18934            }
18935
18936            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
18937        }
18938
18939        final int freezeUser;
18940        if (isUpdatedSystemApp(uninstalledPs)
18941                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
18942            // We're downgrading a system app, which will apply to all users, so
18943            // freeze them all during the downgrade
18944            freezeUser = UserHandle.USER_ALL;
18945        } else {
18946            freezeUser = removeUser;
18947        }
18948
18949        synchronized (mInstallLock) {
18950            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
18951            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
18952                    deleteFlags, "deletePackageX")) {
18953                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
18954                        deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
18955            }
18956            synchronized (mPackages) {
18957                if (res) {
18958                    if (pkg != null) {
18959                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
18960                    }
18961                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
18962                    updateInstantAppInstallerLocked(packageName);
18963                }
18964            }
18965        }
18966
18967        if (res) {
18968            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
18969            info.sendPackageRemovedBroadcasts(killApp);
18970            info.sendSystemPackageUpdatedBroadcasts();
18971            info.sendSystemPackageAppearedBroadcasts();
18972        }
18973        // Force a gc here.
18974        Runtime.getRuntime().gc();
18975        // Delete the resources here after sending the broadcast to let
18976        // other processes clean up before deleting resources.
18977        if (info.args != null) {
18978            synchronized (mInstallLock) {
18979                info.args.doPostDeleteLI(true);
18980            }
18981        }
18982
18983        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18984    }
18985
18986    static class PackageRemovedInfo {
18987        final PackageSender packageSender;
18988        String removedPackage;
18989        String installerPackageName;
18990        int uid = -1;
18991        int removedAppId = -1;
18992        int[] origUsers;
18993        int[] removedUsers = null;
18994        int[] broadcastUsers = null;
18995        SparseArray<Integer> installReasons;
18996        boolean isRemovedPackageSystemUpdate = false;
18997        boolean isUpdate;
18998        boolean dataRemoved;
18999        boolean removedForAllUsers;
19000        boolean isStaticSharedLib;
19001        // Clean up resources deleted packages.
19002        InstallArgs args = null;
19003        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
19004        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
19005
19006        PackageRemovedInfo(PackageSender packageSender) {
19007            this.packageSender = packageSender;
19008        }
19009
19010        void sendPackageRemovedBroadcasts(boolean killApp) {
19011            sendPackageRemovedBroadcastInternal(killApp);
19012            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
19013            for (int i = 0; i < childCount; i++) {
19014                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
19015                childInfo.sendPackageRemovedBroadcastInternal(killApp);
19016            }
19017        }
19018
19019        void sendSystemPackageUpdatedBroadcasts() {
19020            if (isRemovedPackageSystemUpdate) {
19021                sendSystemPackageUpdatedBroadcastsInternal();
19022                final int childCount = (removedChildPackages != null)
19023                        ? removedChildPackages.size() : 0;
19024                for (int i = 0; i < childCount; i++) {
19025                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
19026                    if (childInfo.isRemovedPackageSystemUpdate) {
19027                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
19028                    }
19029                }
19030            }
19031        }
19032
19033        void sendSystemPackageAppearedBroadcasts() {
19034            final int packageCount = (appearedChildPackages != null)
19035                    ? appearedChildPackages.size() : 0;
19036            for (int i = 0; i < packageCount; i++) {
19037                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
19038                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
19039                    true, UserHandle.getAppId(installedInfo.uid),
19040                    installedInfo.newUsers);
19041            }
19042        }
19043
19044        private void sendSystemPackageUpdatedBroadcastsInternal() {
19045            Bundle extras = new Bundle(2);
19046            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
19047            extras.putBoolean(Intent.EXTRA_REPLACING, true);
19048            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
19049                removedPackage, extras, 0, null /*targetPackage*/, null, null);
19050            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
19051                removedPackage, extras, 0, null /*targetPackage*/, null, null);
19052            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
19053                null, null, 0, removedPackage, null, null);
19054            if (installerPackageName != null) {
19055                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
19056                        removedPackage, extras, 0 /*flags*/,
19057                        installerPackageName, null, null);
19058                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
19059                        removedPackage, extras, 0 /*flags*/,
19060                        installerPackageName, null, null);
19061            }
19062        }
19063
19064        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
19065            // Don't send static shared library removal broadcasts as these
19066            // libs are visible only the the apps that depend on them an one
19067            // cannot remove the library if it has a dependency.
19068            if (isStaticSharedLib) {
19069                return;
19070            }
19071            Bundle extras = new Bundle(2);
19072            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
19073            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
19074            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
19075            if (isUpdate || isRemovedPackageSystemUpdate) {
19076                extras.putBoolean(Intent.EXTRA_REPLACING, true);
19077            }
19078            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
19079            if (removedPackage != null) {
19080                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
19081                    removedPackage, extras, 0, null /*targetPackage*/, null, broadcastUsers);
19082                if (installerPackageName != null) {
19083                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
19084                            removedPackage, extras, 0 /*flags*/,
19085                            installerPackageName, null, broadcastUsers);
19086                }
19087                if (dataRemoved && !isRemovedPackageSystemUpdate) {
19088                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
19089                        removedPackage, extras,
19090                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
19091                        null, null, broadcastUsers);
19092                }
19093            }
19094            if (removedAppId >= 0) {
19095                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
19096                    null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
19097                    null, null, broadcastUsers);
19098            }
19099        }
19100
19101        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
19102            removedUsers = userIds;
19103            if (removedUsers == null) {
19104                broadcastUsers = null;
19105                return;
19106            }
19107
19108            broadcastUsers = EMPTY_INT_ARRAY;
19109            for (int i = userIds.length - 1; i >= 0; --i) {
19110                final int userId = userIds[i];
19111                if (deletedPackageSetting.getInstantApp(userId)) {
19112                    continue;
19113                }
19114                broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
19115            }
19116        }
19117    }
19118
19119    /*
19120     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
19121     * flag is not set, the data directory is removed as well.
19122     * make sure this flag is set for partially installed apps. If not its meaningless to
19123     * delete a partially installed application.
19124     */
19125    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
19126            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
19127        String packageName = ps.name;
19128        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
19129        // Retrieve object to delete permissions for shared user later on
19130        final PackageParser.Package deletedPkg;
19131        final PackageSetting deletedPs;
19132        // reader
19133        synchronized (mPackages) {
19134            deletedPkg = mPackages.get(packageName);
19135            deletedPs = mSettings.mPackages.get(packageName);
19136            if (outInfo != null) {
19137                outInfo.removedPackage = packageName;
19138                outInfo.installerPackageName = ps.installerPackageName;
19139                outInfo.isStaticSharedLib = deletedPkg != null
19140                        && deletedPkg.staticSharedLibName != null;
19141                outInfo.populateUsers(deletedPs == null ? null
19142                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
19143            }
19144        }
19145
19146        removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
19147
19148        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
19149            final PackageParser.Package resolvedPkg;
19150            if (deletedPkg != null) {
19151                resolvedPkg = deletedPkg;
19152            } else {
19153                // We don't have a parsed package when it lives on an ejected
19154                // adopted storage device, so fake something together
19155                resolvedPkg = new PackageParser.Package(ps.name);
19156                resolvedPkg.setVolumeUuid(ps.volumeUuid);
19157            }
19158            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
19159                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19160            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
19161            if (outInfo != null) {
19162                outInfo.dataRemoved = true;
19163            }
19164            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
19165        }
19166
19167        int removedAppId = -1;
19168
19169        // writer
19170        synchronized (mPackages) {
19171            boolean installedStateChanged = false;
19172            if (deletedPs != null) {
19173                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
19174                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
19175                    clearDefaultBrowserIfNeeded(packageName);
19176                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
19177                    removedAppId = mSettings.removePackageLPw(packageName);
19178                    if (outInfo != null) {
19179                        outInfo.removedAppId = removedAppId;
19180                    }
19181                    updatePermissionsLPw(deletedPs.name, null, 0);
19182                    if (deletedPs.sharedUser != null) {
19183                        // Remove permissions associated with package. Since runtime
19184                        // permissions are per user we have to kill the removed package
19185                        // or packages running under the shared user of the removed
19186                        // package if revoking the permissions requested only by the removed
19187                        // package is successful and this causes a change in gids.
19188                        for (int userId : UserManagerService.getInstance().getUserIds()) {
19189                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
19190                                    userId);
19191                            if (userIdToKill == UserHandle.USER_ALL
19192                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
19193                                // If gids changed for this user, kill all affected packages.
19194                                mHandler.post(new Runnable() {
19195                                    @Override
19196                                    public void run() {
19197                                        // This has to happen with no lock held.
19198                                        killApplication(deletedPs.name, deletedPs.appId,
19199                                                KILL_APP_REASON_GIDS_CHANGED);
19200                                    }
19201                                });
19202                                break;
19203                            }
19204                        }
19205                    }
19206                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
19207                }
19208                // make sure to preserve per-user disabled state if this removal was just
19209                // a downgrade of a system app to the factory package
19210                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
19211                    if (DEBUG_REMOVE) {
19212                        Slog.d(TAG, "Propagating install state across downgrade");
19213                    }
19214                    for (int userId : allUserHandles) {
19215                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
19216                        if (DEBUG_REMOVE) {
19217                            Slog.d(TAG, "    user " + userId + " => " + installed);
19218                        }
19219                        if (installed != ps.getInstalled(userId)) {
19220                            installedStateChanged = true;
19221                        }
19222                        ps.setInstalled(installed, userId);
19223                    }
19224                }
19225            }
19226            // can downgrade to reader
19227            if (writeSettings) {
19228                // Save settings now
19229                mSettings.writeLPr();
19230            }
19231            if (installedStateChanged) {
19232                mSettings.writeKernelMappingLPr(ps);
19233            }
19234        }
19235        if (removedAppId != -1) {
19236            // A user ID was deleted here. Go through all users and remove it
19237            // from KeyStore.
19238            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
19239        }
19240    }
19241
19242    static boolean locationIsPrivileged(File path) {
19243        try {
19244            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
19245                    .getCanonicalPath();
19246            return path.getCanonicalPath().startsWith(privilegedAppDir);
19247        } catch (IOException e) {
19248            Slog.e(TAG, "Unable to access code path " + path);
19249        }
19250        return false;
19251    }
19252
19253    /*
19254     * Tries to delete system package.
19255     */
19256    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
19257            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
19258            boolean writeSettings) {
19259        if (deletedPs.parentPackageName != null) {
19260            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
19261            return false;
19262        }
19263
19264        final boolean applyUserRestrictions
19265                = (allUserHandles != null) && (outInfo.origUsers != null);
19266        final PackageSetting disabledPs;
19267        // Confirm if the system package has been updated
19268        // An updated system app can be deleted. This will also have to restore
19269        // the system pkg from system partition
19270        // reader
19271        synchronized (mPackages) {
19272            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
19273        }
19274
19275        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
19276                + " disabledPs=" + disabledPs);
19277
19278        if (disabledPs == null) {
19279            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
19280            return false;
19281        } else if (DEBUG_REMOVE) {
19282            Slog.d(TAG, "Deleting system pkg from data partition");
19283        }
19284
19285        if (DEBUG_REMOVE) {
19286            if (applyUserRestrictions) {
19287                Slog.d(TAG, "Remembering install states:");
19288                for (int userId : allUserHandles) {
19289                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
19290                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
19291                }
19292            }
19293        }
19294
19295        // Delete the updated package
19296        outInfo.isRemovedPackageSystemUpdate = true;
19297        if (outInfo.removedChildPackages != null) {
19298            final int childCount = (deletedPs.childPackageNames != null)
19299                    ? deletedPs.childPackageNames.size() : 0;
19300            for (int i = 0; i < childCount; i++) {
19301                String childPackageName = deletedPs.childPackageNames.get(i);
19302                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
19303                        .contains(childPackageName)) {
19304                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19305                            childPackageName);
19306                    if (childInfo != null) {
19307                        childInfo.isRemovedPackageSystemUpdate = true;
19308                    }
19309                }
19310            }
19311        }
19312
19313        if (disabledPs.versionCode < deletedPs.versionCode) {
19314            // Delete data for downgrades
19315            flags &= ~PackageManager.DELETE_KEEP_DATA;
19316        } else {
19317            // Preserve data by setting flag
19318            flags |= PackageManager.DELETE_KEEP_DATA;
19319        }
19320
19321        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
19322                outInfo, writeSettings, disabledPs.pkg);
19323        if (!ret) {
19324            return false;
19325        }
19326
19327        // writer
19328        synchronized (mPackages) {
19329            // Reinstate the old system package
19330            enableSystemPackageLPw(disabledPs.pkg);
19331            // Remove any native libraries from the upgraded package.
19332            removeNativeBinariesLI(deletedPs);
19333        }
19334
19335        // Install the system package
19336        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
19337        int parseFlags = mDefParseFlags
19338                | PackageParser.PARSE_MUST_BE_APK
19339                | PackageParser.PARSE_IS_SYSTEM
19340                | PackageParser.PARSE_IS_SYSTEM_DIR;
19341        if (locationIsPrivileged(disabledPs.codePath)) {
19342            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
19343        }
19344
19345        final PackageParser.Package newPkg;
19346        try {
19347            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */,
19348                0 /* currentTime */, null);
19349        } catch (PackageManagerException e) {
19350            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
19351                    + e.getMessage());
19352            return false;
19353        }
19354
19355        try {
19356            // update shared libraries for the newly re-installed system package
19357            updateSharedLibrariesLPr(newPkg, null);
19358        } catch (PackageManagerException e) {
19359            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
19360        }
19361
19362        prepareAppDataAfterInstallLIF(newPkg);
19363
19364        // writer
19365        synchronized (mPackages) {
19366            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
19367
19368            // Propagate the permissions state as we do not want to drop on the floor
19369            // runtime permissions. The update permissions method below will take
19370            // care of removing obsolete permissions and grant install permissions.
19371            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
19372            updatePermissionsLPw(newPkg.packageName, newPkg,
19373                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
19374
19375            if (applyUserRestrictions) {
19376                boolean installedStateChanged = false;
19377                if (DEBUG_REMOVE) {
19378                    Slog.d(TAG, "Propagating install state across reinstall");
19379                }
19380                for (int userId : allUserHandles) {
19381                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
19382                    if (DEBUG_REMOVE) {
19383                        Slog.d(TAG, "    user " + userId + " => " + installed);
19384                    }
19385                    if (installed != ps.getInstalled(userId)) {
19386                        installedStateChanged = true;
19387                    }
19388                    ps.setInstalled(installed, userId);
19389
19390                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19391                }
19392                // Regardless of writeSettings we need to ensure that this restriction
19393                // state propagation is persisted
19394                mSettings.writeAllUsersPackageRestrictionsLPr();
19395                if (installedStateChanged) {
19396                    mSettings.writeKernelMappingLPr(ps);
19397                }
19398            }
19399            // can downgrade to reader here
19400            if (writeSettings) {
19401                mSettings.writeLPr();
19402            }
19403        }
19404        return true;
19405    }
19406
19407    private boolean deleteInstalledPackageLIF(PackageSetting ps,
19408            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
19409            PackageRemovedInfo outInfo, boolean writeSettings,
19410            PackageParser.Package replacingPackage) {
19411        synchronized (mPackages) {
19412            if (outInfo != null) {
19413                outInfo.uid = ps.appId;
19414            }
19415
19416            if (outInfo != null && outInfo.removedChildPackages != null) {
19417                final int childCount = (ps.childPackageNames != null)
19418                        ? ps.childPackageNames.size() : 0;
19419                for (int i = 0; i < childCount; i++) {
19420                    String childPackageName = ps.childPackageNames.get(i);
19421                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
19422                    if (childPs == null) {
19423                        return false;
19424                    }
19425                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19426                            childPackageName);
19427                    if (childInfo != null) {
19428                        childInfo.uid = childPs.appId;
19429                    }
19430                }
19431            }
19432        }
19433
19434        // Delete package data from internal structures and also remove data if flag is set
19435        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
19436
19437        // Delete the child packages data
19438        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
19439        for (int i = 0; i < childCount; i++) {
19440            PackageSetting childPs;
19441            synchronized (mPackages) {
19442                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
19443            }
19444            if (childPs != null) {
19445                PackageRemovedInfo childOutInfo = (outInfo != null
19446                        && outInfo.removedChildPackages != null)
19447                        ? outInfo.removedChildPackages.get(childPs.name) : null;
19448                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
19449                        && (replacingPackage != null
19450                        && !replacingPackage.hasChildPackage(childPs.name))
19451                        ? flags & ~DELETE_KEEP_DATA : flags;
19452                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
19453                        deleteFlags, writeSettings);
19454            }
19455        }
19456
19457        // Delete application code and resources only for parent packages
19458        if (ps.parentPackageName == null) {
19459            if (deleteCodeAndResources && (outInfo != null)) {
19460                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
19461                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
19462                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
19463            }
19464        }
19465
19466        return true;
19467    }
19468
19469    @Override
19470    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
19471            int userId) {
19472        mContext.enforceCallingOrSelfPermission(
19473                android.Manifest.permission.DELETE_PACKAGES, null);
19474        synchronized (mPackages) {
19475            // Cannot block uninstall of static shared libs as they are
19476            // considered a part of the using app (emulating static linking).
19477            // Also static libs are installed always on internal storage.
19478            PackageParser.Package pkg = mPackages.get(packageName);
19479            if (pkg != null && pkg.staticSharedLibName != null) {
19480                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
19481                        + " providing static shared library: " + pkg.staticSharedLibName);
19482                return false;
19483            }
19484            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
19485            mSettings.writePackageRestrictionsLPr(userId);
19486        }
19487        return true;
19488    }
19489
19490    @Override
19491    public boolean getBlockUninstallForUser(String packageName, int userId) {
19492        synchronized (mPackages) {
19493            final PackageSetting ps = mSettings.mPackages.get(packageName);
19494            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
19495                return false;
19496            }
19497            return mSettings.getBlockUninstallLPr(userId, packageName);
19498        }
19499    }
19500
19501    @Override
19502    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
19503        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
19504        synchronized (mPackages) {
19505            PackageSetting ps = mSettings.mPackages.get(packageName);
19506            if (ps == null) {
19507                Log.w(TAG, "Package doesn't exist: " + packageName);
19508                return false;
19509            }
19510            if (systemUserApp) {
19511                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
19512            } else {
19513                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
19514            }
19515            mSettings.writeLPr();
19516        }
19517        return true;
19518    }
19519
19520    /*
19521     * This method handles package deletion in general
19522     */
19523    private boolean deletePackageLIF(String packageName, UserHandle user,
19524            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
19525            PackageRemovedInfo outInfo, boolean writeSettings,
19526            PackageParser.Package replacingPackage) {
19527        if (packageName == null) {
19528            Slog.w(TAG, "Attempt to delete null packageName.");
19529            return false;
19530        }
19531
19532        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
19533
19534        PackageSetting ps;
19535        synchronized (mPackages) {
19536            ps = mSettings.mPackages.get(packageName);
19537            if (ps == null) {
19538                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19539                return false;
19540            }
19541
19542            if (ps.parentPackageName != null && (!isSystemApp(ps)
19543                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
19544                if (DEBUG_REMOVE) {
19545                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
19546                            + ((user == null) ? UserHandle.USER_ALL : user));
19547                }
19548                final int removedUserId = (user != null) ? user.getIdentifier()
19549                        : UserHandle.USER_ALL;
19550                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
19551                    return false;
19552                }
19553                markPackageUninstalledForUserLPw(ps, user);
19554                scheduleWritePackageRestrictionsLocked(user);
19555                return true;
19556            }
19557        }
19558
19559        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
19560                && user.getIdentifier() != UserHandle.USER_ALL)) {
19561            // The caller is asking that the package only be deleted for a single
19562            // user.  To do this, we just mark its uninstalled state and delete
19563            // its data. If this is a system app, we only allow this to happen if
19564            // they have set the special DELETE_SYSTEM_APP which requests different
19565            // semantics than normal for uninstalling system apps.
19566            markPackageUninstalledForUserLPw(ps, user);
19567
19568            if (!isSystemApp(ps)) {
19569                // Do not uninstall the APK if an app should be cached
19570                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
19571                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
19572                    // Other user still have this package installed, so all
19573                    // we need to do is clear this user's data and save that
19574                    // it is uninstalled.
19575                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
19576                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
19577                        return false;
19578                    }
19579                    scheduleWritePackageRestrictionsLocked(user);
19580                    return true;
19581                } else {
19582                    // We need to set it back to 'installed' so the uninstall
19583                    // broadcasts will be sent correctly.
19584                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
19585                    ps.setInstalled(true, user.getIdentifier());
19586                    mSettings.writeKernelMappingLPr(ps);
19587                }
19588            } else {
19589                // This is a system app, so we assume that the
19590                // other users still have this package installed, so all
19591                // we need to do is clear this user's data and save that
19592                // it is uninstalled.
19593                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
19594                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
19595                    return false;
19596                }
19597                scheduleWritePackageRestrictionsLocked(user);
19598                return true;
19599            }
19600        }
19601
19602        // If we are deleting a composite package for all users, keep track
19603        // of result for each child.
19604        if (ps.childPackageNames != null && outInfo != null) {
19605            synchronized (mPackages) {
19606                final int childCount = ps.childPackageNames.size();
19607                outInfo.removedChildPackages = new ArrayMap<>(childCount);
19608                for (int i = 0; i < childCount; i++) {
19609                    String childPackageName = ps.childPackageNames.get(i);
19610                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
19611                    childInfo.removedPackage = childPackageName;
19612                    childInfo.installerPackageName = ps.installerPackageName;
19613                    outInfo.removedChildPackages.put(childPackageName, childInfo);
19614                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
19615                    if (childPs != null) {
19616                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
19617                    }
19618                }
19619            }
19620        }
19621
19622        boolean ret = false;
19623        if (isSystemApp(ps)) {
19624            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
19625            // When an updated system application is deleted we delete the existing resources
19626            // as well and fall back to existing code in system partition
19627            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
19628        } else {
19629            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
19630            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
19631                    outInfo, writeSettings, replacingPackage);
19632        }
19633
19634        // Take a note whether we deleted the package for all users
19635        if (outInfo != null) {
19636            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
19637            if (outInfo.removedChildPackages != null) {
19638                synchronized (mPackages) {
19639                    final int childCount = outInfo.removedChildPackages.size();
19640                    for (int i = 0; i < childCount; i++) {
19641                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
19642                        if (childInfo != null) {
19643                            childInfo.removedForAllUsers = mPackages.get(
19644                                    childInfo.removedPackage) == null;
19645                        }
19646                    }
19647                }
19648            }
19649            // If we uninstalled an update to a system app there may be some
19650            // child packages that appeared as they are declared in the system
19651            // app but were not declared in the update.
19652            if (isSystemApp(ps)) {
19653                synchronized (mPackages) {
19654                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
19655                    final int childCount = (updatedPs.childPackageNames != null)
19656                            ? updatedPs.childPackageNames.size() : 0;
19657                    for (int i = 0; i < childCount; i++) {
19658                        String childPackageName = updatedPs.childPackageNames.get(i);
19659                        if (outInfo.removedChildPackages == null
19660                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
19661                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
19662                            if (childPs == null) {
19663                                continue;
19664                            }
19665                            PackageInstalledInfo installRes = new PackageInstalledInfo();
19666                            installRes.name = childPackageName;
19667                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
19668                            installRes.pkg = mPackages.get(childPackageName);
19669                            installRes.uid = childPs.pkg.applicationInfo.uid;
19670                            if (outInfo.appearedChildPackages == null) {
19671                                outInfo.appearedChildPackages = new ArrayMap<>();
19672                            }
19673                            outInfo.appearedChildPackages.put(childPackageName, installRes);
19674                        }
19675                    }
19676                }
19677            }
19678        }
19679
19680        return ret;
19681    }
19682
19683    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
19684        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
19685                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
19686        for (int nextUserId : userIds) {
19687            if (DEBUG_REMOVE) {
19688                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
19689            }
19690            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
19691                    false /*installed*/,
19692                    true /*stopped*/,
19693                    true /*notLaunched*/,
19694                    false /*hidden*/,
19695                    false /*suspended*/,
19696                    false /*instantApp*/,
19697                    null /*lastDisableAppCaller*/,
19698                    null /*enabledComponents*/,
19699                    null /*disabledComponents*/,
19700                    ps.readUserState(nextUserId).domainVerificationStatus,
19701                    0, PackageManager.INSTALL_REASON_UNKNOWN);
19702        }
19703        mSettings.writeKernelMappingLPr(ps);
19704    }
19705
19706    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
19707            PackageRemovedInfo outInfo) {
19708        final PackageParser.Package pkg;
19709        synchronized (mPackages) {
19710            pkg = mPackages.get(ps.name);
19711        }
19712
19713        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
19714                : new int[] {userId};
19715        for (int nextUserId : userIds) {
19716            if (DEBUG_REMOVE) {
19717                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
19718                        + nextUserId);
19719            }
19720
19721            destroyAppDataLIF(pkg, userId,
19722                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19723            destroyAppProfilesLIF(pkg, userId);
19724            clearDefaultBrowserIfNeededForUser(ps.name, userId);
19725            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
19726            schedulePackageCleaning(ps.name, nextUserId, false);
19727            synchronized (mPackages) {
19728                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
19729                    scheduleWritePackageRestrictionsLocked(nextUserId);
19730                }
19731                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
19732            }
19733        }
19734
19735        if (outInfo != null) {
19736            outInfo.removedPackage = ps.name;
19737            outInfo.installerPackageName = ps.installerPackageName;
19738            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
19739            outInfo.removedAppId = ps.appId;
19740            outInfo.removedUsers = userIds;
19741            outInfo.broadcastUsers = userIds;
19742        }
19743
19744        return true;
19745    }
19746
19747    private final class ClearStorageConnection implements ServiceConnection {
19748        IMediaContainerService mContainerService;
19749
19750        @Override
19751        public void onServiceConnected(ComponentName name, IBinder service) {
19752            synchronized (this) {
19753                mContainerService = IMediaContainerService.Stub
19754                        .asInterface(Binder.allowBlocking(service));
19755                notifyAll();
19756            }
19757        }
19758
19759        @Override
19760        public void onServiceDisconnected(ComponentName name) {
19761        }
19762    }
19763
19764    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
19765        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
19766
19767        final boolean mounted;
19768        if (Environment.isExternalStorageEmulated()) {
19769            mounted = true;
19770        } else {
19771            final String status = Environment.getExternalStorageState();
19772
19773            mounted = status.equals(Environment.MEDIA_MOUNTED)
19774                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
19775        }
19776
19777        if (!mounted) {
19778            return;
19779        }
19780
19781        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
19782        int[] users;
19783        if (userId == UserHandle.USER_ALL) {
19784            users = sUserManager.getUserIds();
19785        } else {
19786            users = new int[] { userId };
19787        }
19788        final ClearStorageConnection conn = new ClearStorageConnection();
19789        if (mContext.bindServiceAsUser(
19790                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
19791            try {
19792                for (int curUser : users) {
19793                    long timeout = SystemClock.uptimeMillis() + 5000;
19794                    synchronized (conn) {
19795                        long now;
19796                        while (conn.mContainerService == null &&
19797                                (now = SystemClock.uptimeMillis()) < timeout) {
19798                            try {
19799                                conn.wait(timeout - now);
19800                            } catch (InterruptedException e) {
19801                            }
19802                        }
19803                    }
19804                    if (conn.mContainerService == null) {
19805                        return;
19806                    }
19807
19808                    final UserEnvironment userEnv = new UserEnvironment(curUser);
19809                    clearDirectory(conn.mContainerService,
19810                            userEnv.buildExternalStorageAppCacheDirs(packageName));
19811                    if (allData) {
19812                        clearDirectory(conn.mContainerService,
19813                                userEnv.buildExternalStorageAppDataDirs(packageName));
19814                        clearDirectory(conn.mContainerService,
19815                                userEnv.buildExternalStorageAppMediaDirs(packageName));
19816                    }
19817                }
19818            } finally {
19819                mContext.unbindService(conn);
19820            }
19821        }
19822    }
19823
19824    @Override
19825    public void clearApplicationProfileData(String packageName) {
19826        enforceSystemOrRoot("Only the system can clear all profile data");
19827
19828        final PackageParser.Package pkg;
19829        synchronized (mPackages) {
19830            pkg = mPackages.get(packageName);
19831        }
19832
19833        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
19834            synchronized (mInstallLock) {
19835                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
19836            }
19837        }
19838    }
19839
19840    @Override
19841    public void clearApplicationUserData(final String packageName,
19842            final IPackageDataObserver observer, final int userId) {
19843        mContext.enforceCallingOrSelfPermission(
19844                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
19845
19846        final int callingUid = Binder.getCallingUid();
19847        enforceCrossUserPermission(callingUid, userId,
19848                true /* requireFullPermission */, false /* checkShell */, "clear application data");
19849
19850        final PackageSetting ps = mSettings.getPackageLPr(packageName);
19851        if (ps != null && filterAppAccessLPr(ps, callingUid, userId)) {
19852            return;
19853        }
19854        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
19855            throw new SecurityException("Cannot clear data for a protected package: "
19856                    + packageName);
19857        }
19858        // Queue up an async operation since the package deletion may take a little while.
19859        mHandler.post(new Runnable() {
19860            public void run() {
19861                mHandler.removeCallbacks(this);
19862                final boolean succeeded;
19863                try (PackageFreezer freezer = freezePackage(packageName,
19864                        "clearApplicationUserData")) {
19865                    synchronized (mInstallLock) {
19866                        succeeded = clearApplicationUserDataLIF(packageName, userId);
19867                    }
19868                    clearExternalStorageDataSync(packageName, userId, true);
19869                    synchronized (mPackages) {
19870                        mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
19871                                packageName, userId);
19872                    }
19873                }
19874                if (succeeded) {
19875                    // invoke DeviceStorageMonitor's update method to clear any notifications
19876                    DeviceStorageMonitorInternal dsm = LocalServices
19877                            .getService(DeviceStorageMonitorInternal.class);
19878                    if (dsm != null) {
19879                        dsm.checkMemory();
19880                    }
19881                }
19882                if(observer != null) {
19883                    try {
19884                        observer.onRemoveCompleted(packageName, succeeded);
19885                    } catch (RemoteException e) {
19886                        Log.i(TAG, "Observer no longer exists.");
19887                    }
19888                } //end if observer
19889            } //end run
19890        });
19891    }
19892
19893    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
19894        if (packageName == null) {
19895            Slog.w(TAG, "Attempt to delete null packageName.");
19896            return false;
19897        }
19898
19899        // Try finding details about the requested package
19900        PackageParser.Package pkg;
19901        synchronized (mPackages) {
19902            pkg = mPackages.get(packageName);
19903            if (pkg == null) {
19904                final PackageSetting ps = mSettings.mPackages.get(packageName);
19905                if (ps != null) {
19906                    pkg = ps.pkg;
19907                }
19908            }
19909
19910            if (pkg == null) {
19911                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19912                return false;
19913            }
19914
19915            PackageSetting ps = (PackageSetting) pkg.mExtras;
19916            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19917        }
19918
19919        clearAppDataLIF(pkg, userId,
19920                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19921
19922        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
19923        removeKeystoreDataIfNeeded(userId, appId);
19924
19925        UserManagerInternal umInternal = getUserManagerInternal();
19926        final int flags;
19927        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
19928            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19929        } else if (umInternal.isUserRunning(userId)) {
19930            flags = StorageManager.FLAG_STORAGE_DE;
19931        } else {
19932            flags = 0;
19933        }
19934        prepareAppDataContentsLIF(pkg, userId, flags);
19935
19936        return true;
19937    }
19938
19939    /**
19940     * Reverts user permission state changes (permissions and flags) in
19941     * all packages for a given user.
19942     *
19943     * @param userId The device user for which to do a reset.
19944     */
19945    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
19946        final int packageCount = mPackages.size();
19947        for (int i = 0; i < packageCount; i++) {
19948            PackageParser.Package pkg = mPackages.valueAt(i);
19949            PackageSetting ps = (PackageSetting) pkg.mExtras;
19950            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19951        }
19952    }
19953
19954    private void resetNetworkPolicies(int userId) {
19955        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
19956    }
19957
19958    /**
19959     * Reverts user permission state changes (permissions and flags).
19960     *
19961     * @param ps The package for which to reset.
19962     * @param userId The device user for which to do a reset.
19963     */
19964    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
19965            final PackageSetting ps, final int userId) {
19966        if (ps.pkg == null) {
19967            return;
19968        }
19969
19970        // These are flags that can change base on user actions.
19971        final int userSettableMask = FLAG_PERMISSION_USER_SET
19972                | FLAG_PERMISSION_USER_FIXED
19973                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
19974                | FLAG_PERMISSION_REVIEW_REQUIRED;
19975
19976        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
19977                | FLAG_PERMISSION_POLICY_FIXED;
19978
19979        boolean writeInstallPermissions = false;
19980        boolean writeRuntimePermissions = false;
19981
19982        final int permissionCount = ps.pkg.requestedPermissions.size();
19983        for (int i = 0; i < permissionCount; i++) {
19984            String permission = ps.pkg.requestedPermissions.get(i);
19985
19986            BasePermission bp = mSettings.mPermissions.get(permission);
19987            if (bp == null) {
19988                continue;
19989            }
19990
19991            // If shared user we just reset the state to which only this app contributed.
19992            if (ps.sharedUser != null) {
19993                boolean used = false;
19994                final int packageCount = ps.sharedUser.packages.size();
19995                for (int j = 0; j < packageCount; j++) {
19996                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
19997                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
19998                            && pkg.pkg.requestedPermissions.contains(permission)) {
19999                        used = true;
20000                        break;
20001                    }
20002                }
20003                if (used) {
20004                    continue;
20005                }
20006            }
20007
20008            PermissionsState permissionsState = ps.getPermissionsState();
20009
20010            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
20011
20012            // Always clear the user settable flags.
20013            final boolean hasInstallState = permissionsState.getInstallPermissionState(
20014                    bp.name) != null;
20015            // If permission review is enabled and this is a legacy app, mark the
20016            // permission as requiring a review as this is the initial state.
20017            int flags = 0;
20018            if (mPermissionReviewRequired
20019                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
20020                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
20021            }
20022            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
20023                if (hasInstallState) {
20024                    writeInstallPermissions = true;
20025                } else {
20026                    writeRuntimePermissions = true;
20027                }
20028            }
20029
20030            // Below is only runtime permission handling.
20031            if (!bp.isRuntime()) {
20032                continue;
20033            }
20034
20035            // Never clobber system or policy.
20036            if ((oldFlags & policyOrSystemFlags) != 0) {
20037                continue;
20038            }
20039
20040            // If this permission was granted by default, make sure it is.
20041            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
20042                if (permissionsState.grantRuntimePermission(bp, userId)
20043                        != PERMISSION_OPERATION_FAILURE) {
20044                    writeRuntimePermissions = true;
20045                }
20046            // If permission review is enabled the permissions for a legacy apps
20047            // are represented as constantly granted runtime ones, so don't revoke.
20048            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
20049                // Otherwise, reset the permission.
20050                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
20051                switch (revokeResult) {
20052                    case PERMISSION_OPERATION_SUCCESS:
20053                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
20054                        writeRuntimePermissions = true;
20055                        final int appId = ps.appId;
20056                        mHandler.post(new Runnable() {
20057                            @Override
20058                            public void run() {
20059                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
20060                            }
20061                        });
20062                    } break;
20063                }
20064            }
20065        }
20066
20067        // Synchronously write as we are taking permissions away.
20068        if (writeRuntimePermissions) {
20069            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
20070        }
20071
20072        // Synchronously write as we are taking permissions away.
20073        if (writeInstallPermissions) {
20074            mSettings.writeLPr();
20075        }
20076    }
20077
20078    /**
20079     * Remove entries from the keystore daemon. Will only remove it if the
20080     * {@code appId} is valid.
20081     */
20082    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
20083        if (appId < 0) {
20084            return;
20085        }
20086
20087        final KeyStore keyStore = KeyStore.getInstance();
20088        if (keyStore != null) {
20089            if (userId == UserHandle.USER_ALL) {
20090                for (final int individual : sUserManager.getUserIds()) {
20091                    keyStore.clearUid(UserHandle.getUid(individual, appId));
20092                }
20093            } else {
20094                keyStore.clearUid(UserHandle.getUid(userId, appId));
20095            }
20096        } else {
20097            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
20098        }
20099    }
20100
20101    @Override
20102    public void deleteApplicationCacheFiles(final String packageName,
20103            final IPackageDataObserver observer) {
20104        final int userId = UserHandle.getCallingUserId();
20105        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
20106    }
20107
20108    @Override
20109    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
20110            final IPackageDataObserver observer) {
20111        final int callingUid = Binder.getCallingUid();
20112        mContext.enforceCallingOrSelfPermission(
20113                android.Manifest.permission.DELETE_CACHE_FILES, null);
20114        enforceCrossUserPermission(callingUid, userId,
20115                /* requireFullPermission= */ true, /* checkShell= */ false,
20116                "delete application cache files");
20117        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
20118                android.Manifest.permission.ACCESS_INSTANT_APPS);
20119
20120        final PackageParser.Package pkg;
20121        synchronized (mPackages) {
20122            pkg = mPackages.get(packageName);
20123        }
20124
20125        // Queue up an async operation since the package deletion may take a little while.
20126        mHandler.post(new Runnable() {
20127            public void run() {
20128                final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
20129                boolean doClearData = true;
20130                if (ps != null) {
20131                    final boolean targetIsInstantApp =
20132                            ps.getInstantApp(UserHandle.getUserId(callingUid));
20133                    doClearData = !targetIsInstantApp
20134                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
20135                }
20136                if (doClearData) {
20137                    synchronized (mInstallLock) {
20138                        final int flags = StorageManager.FLAG_STORAGE_DE
20139                                | StorageManager.FLAG_STORAGE_CE;
20140                        // We're only clearing cache files, so we don't care if the
20141                        // app is unfrozen and still able to run
20142                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
20143                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20144                    }
20145                    clearExternalStorageDataSync(packageName, userId, false);
20146                }
20147                if (observer != null) {
20148                    try {
20149                        observer.onRemoveCompleted(packageName, true);
20150                    } catch (RemoteException e) {
20151                        Log.i(TAG, "Observer no longer exists.");
20152                    }
20153                }
20154            }
20155        });
20156    }
20157
20158    @Override
20159    public void getPackageSizeInfo(final String packageName, int userHandle,
20160            final IPackageStatsObserver observer) {
20161        throw new UnsupportedOperationException(
20162                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
20163    }
20164
20165    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
20166        final PackageSetting ps;
20167        synchronized (mPackages) {
20168            ps = mSettings.mPackages.get(packageName);
20169            if (ps == null) {
20170                Slog.w(TAG, "Failed to find settings for " + packageName);
20171                return false;
20172            }
20173        }
20174
20175        final String[] packageNames = { packageName };
20176        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
20177        final String[] codePaths = { ps.codePathString };
20178
20179        try {
20180            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
20181                    ps.appId, ceDataInodes, codePaths, stats);
20182
20183            // For now, ignore code size of packages on system partition
20184            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
20185                stats.codeSize = 0;
20186            }
20187
20188            // External clients expect these to be tracked separately
20189            stats.dataSize -= stats.cacheSize;
20190
20191        } catch (InstallerException e) {
20192            Slog.w(TAG, String.valueOf(e));
20193            return false;
20194        }
20195
20196        return true;
20197    }
20198
20199    private int getUidTargetSdkVersionLockedLPr(int uid) {
20200        Object obj = mSettings.getUserIdLPr(uid);
20201        if (obj instanceof SharedUserSetting) {
20202            final SharedUserSetting sus = (SharedUserSetting) obj;
20203            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
20204            final Iterator<PackageSetting> it = sus.packages.iterator();
20205            while (it.hasNext()) {
20206                final PackageSetting ps = it.next();
20207                if (ps.pkg != null) {
20208                    int v = ps.pkg.applicationInfo.targetSdkVersion;
20209                    if (v < vers) vers = v;
20210                }
20211            }
20212            return vers;
20213        } else if (obj instanceof PackageSetting) {
20214            final PackageSetting ps = (PackageSetting) obj;
20215            if (ps.pkg != null) {
20216                return ps.pkg.applicationInfo.targetSdkVersion;
20217            }
20218        }
20219        return Build.VERSION_CODES.CUR_DEVELOPMENT;
20220    }
20221
20222    @Override
20223    public void addPreferredActivity(IntentFilter filter, int match,
20224            ComponentName[] set, ComponentName activity, int userId) {
20225        addPreferredActivityInternal(filter, match, set, activity, true, userId,
20226                "Adding preferred");
20227    }
20228
20229    private void addPreferredActivityInternal(IntentFilter filter, int match,
20230            ComponentName[] set, ComponentName activity, boolean always, int userId,
20231            String opname) {
20232        // writer
20233        int callingUid = Binder.getCallingUid();
20234        enforceCrossUserPermission(callingUid, userId,
20235                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
20236        if (filter.countActions() == 0) {
20237            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20238            return;
20239        }
20240        synchronized (mPackages) {
20241            if (mContext.checkCallingOrSelfPermission(
20242                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20243                    != PackageManager.PERMISSION_GRANTED) {
20244                if (getUidTargetSdkVersionLockedLPr(callingUid)
20245                        < Build.VERSION_CODES.FROYO) {
20246                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
20247                            + callingUid);
20248                    return;
20249                }
20250                mContext.enforceCallingOrSelfPermission(
20251                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20252            }
20253
20254            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
20255            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
20256                    + userId + ":");
20257            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20258            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
20259            scheduleWritePackageRestrictionsLocked(userId);
20260            postPreferredActivityChangedBroadcast(userId);
20261        }
20262    }
20263
20264    private void postPreferredActivityChangedBroadcast(int userId) {
20265        mHandler.post(() -> {
20266            final IActivityManager am = ActivityManager.getService();
20267            if (am == null) {
20268                return;
20269            }
20270
20271            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
20272            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
20273            try {
20274                am.broadcastIntent(null, intent, null, null,
20275                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
20276                        null, false, false, userId);
20277            } catch (RemoteException e) {
20278            }
20279        });
20280    }
20281
20282    @Override
20283    public void replacePreferredActivity(IntentFilter filter, int match,
20284            ComponentName[] set, ComponentName activity, int userId) {
20285        if (filter.countActions() != 1) {
20286            throw new IllegalArgumentException(
20287                    "replacePreferredActivity expects filter to have only 1 action.");
20288        }
20289        if (filter.countDataAuthorities() != 0
20290                || filter.countDataPaths() != 0
20291                || filter.countDataSchemes() > 1
20292                || filter.countDataTypes() != 0) {
20293            throw new IllegalArgumentException(
20294                    "replacePreferredActivity expects filter to have no data authorities, " +
20295                    "paths, or types; and at most one scheme.");
20296        }
20297
20298        final int callingUid = Binder.getCallingUid();
20299        enforceCrossUserPermission(callingUid, userId,
20300                true /* requireFullPermission */, false /* checkShell */,
20301                "replace preferred activity");
20302        synchronized (mPackages) {
20303            if (mContext.checkCallingOrSelfPermission(
20304                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20305                    != PackageManager.PERMISSION_GRANTED) {
20306                if (getUidTargetSdkVersionLockedLPr(callingUid)
20307                        < Build.VERSION_CODES.FROYO) {
20308                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
20309                            + Binder.getCallingUid());
20310                    return;
20311                }
20312                mContext.enforceCallingOrSelfPermission(
20313                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20314            }
20315
20316            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20317            if (pir != null) {
20318                // Get all of the existing entries that exactly match this filter.
20319                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
20320                if (existing != null && existing.size() == 1) {
20321                    PreferredActivity cur = existing.get(0);
20322                    if (DEBUG_PREFERRED) {
20323                        Slog.i(TAG, "Checking replace of preferred:");
20324                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20325                        if (!cur.mPref.mAlways) {
20326                            Slog.i(TAG, "  -- CUR; not mAlways!");
20327                        } else {
20328                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
20329                            Slog.i(TAG, "  -- CUR: mSet="
20330                                    + Arrays.toString(cur.mPref.mSetComponents));
20331                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
20332                            Slog.i(TAG, "  -- NEW: mMatch="
20333                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
20334                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
20335                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
20336                        }
20337                    }
20338                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
20339                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
20340                            && cur.mPref.sameSet(set)) {
20341                        // Setting the preferred activity to what it happens to be already
20342                        if (DEBUG_PREFERRED) {
20343                            Slog.i(TAG, "Replacing with same preferred activity "
20344                                    + cur.mPref.mShortComponent + " for user "
20345                                    + userId + ":");
20346                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20347                        }
20348                        return;
20349                    }
20350                }
20351
20352                if (existing != null) {
20353                    if (DEBUG_PREFERRED) {
20354                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
20355                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20356                    }
20357                    for (int i = 0; i < existing.size(); i++) {
20358                        PreferredActivity pa = existing.get(i);
20359                        if (DEBUG_PREFERRED) {
20360                            Slog.i(TAG, "Removing existing preferred activity "
20361                                    + pa.mPref.mComponent + ":");
20362                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
20363                        }
20364                        pir.removeFilter(pa);
20365                    }
20366                }
20367            }
20368            addPreferredActivityInternal(filter, match, set, activity, true, userId,
20369                    "Replacing preferred");
20370        }
20371    }
20372
20373    @Override
20374    public void clearPackagePreferredActivities(String packageName) {
20375        final int callingUid = Binder.getCallingUid();
20376        if (getInstantAppPackageName(callingUid) != null) {
20377            return;
20378        }
20379        // writer
20380        synchronized (mPackages) {
20381            PackageParser.Package pkg = mPackages.get(packageName);
20382            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
20383                if (mContext.checkCallingOrSelfPermission(
20384                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20385                        != PackageManager.PERMISSION_GRANTED) {
20386                    if (getUidTargetSdkVersionLockedLPr(callingUid)
20387                            < Build.VERSION_CODES.FROYO) {
20388                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
20389                                + callingUid);
20390                        return;
20391                    }
20392                    mContext.enforceCallingOrSelfPermission(
20393                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20394                }
20395            }
20396            final PackageSetting ps = mSettings.getPackageLPr(packageName);
20397            if (ps != null
20398                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20399                return;
20400            }
20401            int user = UserHandle.getCallingUserId();
20402            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
20403                scheduleWritePackageRestrictionsLocked(user);
20404            }
20405        }
20406    }
20407
20408    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20409    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
20410        ArrayList<PreferredActivity> removed = null;
20411        boolean changed = false;
20412        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20413            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
20414            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20415            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
20416                continue;
20417            }
20418            Iterator<PreferredActivity> it = pir.filterIterator();
20419            while (it.hasNext()) {
20420                PreferredActivity pa = it.next();
20421                // Mark entry for removal only if it matches the package name
20422                // and the entry is of type "always".
20423                if (packageName == null ||
20424                        (pa.mPref.mComponent.getPackageName().equals(packageName)
20425                                && pa.mPref.mAlways)) {
20426                    if (removed == null) {
20427                        removed = new ArrayList<PreferredActivity>();
20428                    }
20429                    removed.add(pa);
20430                }
20431            }
20432            if (removed != null) {
20433                for (int j=0; j<removed.size(); j++) {
20434                    PreferredActivity pa = removed.get(j);
20435                    pir.removeFilter(pa);
20436                }
20437                changed = true;
20438            }
20439        }
20440        if (changed) {
20441            postPreferredActivityChangedBroadcast(userId);
20442        }
20443        return changed;
20444    }
20445
20446    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20447    private void clearIntentFilterVerificationsLPw(int userId) {
20448        final int packageCount = mPackages.size();
20449        for (int i = 0; i < packageCount; i++) {
20450            PackageParser.Package pkg = mPackages.valueAt(i);
20451            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
20452        }
20453    }
20454
20455    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20456    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
20457        if (userId == UserHandle.USER_ALL) {
20458            if (mSettings.removeIntentFilterVerificationLPw(packageName,
20459                    sUserManager.getUserIds())) {
20460                for (int oneUserId : sUserManager.getUserIds()) {
20461                    scheduleWritePackageRestrictionsLocked(oneUserId);
20462                }
20463            }
20464        } else {
20465            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
20466                scheduleWritePackageRestrictionsLocked(userId);
20467            }
20468        }
20469    }
20470
20471    /** Clears state for all users, and touches intent filter verification policy */
20472    void clearDefaultBrowserIfNeeded(String packageName) {
20473        for (int oneUserId : sUserManager.getUserIds()) {
20474            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
20475        }
20476    }
20477
20478    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
20479        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
20480        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
20481            if (packageName.equals(defaultBrowserPackageName)) {
20482                setDefaultBrowserPackageName(null, userId);
20483            }
20484        }
20485    }
20486
20487    @Override
20488    public void resetApplicationPreferences(int userId) {
20489        mContext.enforceCallingOrSelfPermission(
20490                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20491        final long identity = Binder.clearCallingIdentity();
20492        // writer
20493        try {
20494            synchronized (mPackages) {
20495                clearPackagePreferredActivitiesLPw(null, userId);
20496                mSettings.applyDefaultPreferredAppsLPw(this, userId);
20497                // TODO: We have to reset the default SMS and Phone. This requires
20498                // significant refactoring to keep all default apps in the package
20499                // manager (cleaner but more work) or have the services provide
20500                // callbacks to the package manager to request a default app reset.
20501                applyFactoryDefaultBrowserLPw(userId);
20502                clearIntentFilterVerificationsLPw(userId);
20503                primeDomainVerificationsLPw(userId);
20504                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
20505                scheduleWritePackageRestrictionsLocked(userId);
20506            }
20507            resetNetworkPolicies(userId);
20508        } finally {
20509            Binder.restoreCallingIdentity(identity);
20510        }
20511    }
20512
20513    @Override
20514    public int getPreferredActivities(List<IntentFilter> outFilters,
20515            List<ComponentName> outActivities, String packageName) {
20516        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20517            return 0;
20518        }
20519        int num = 0;
20520        final int userId = UserHandle.getCallingUserId();
20521        // reader
20522        synchronized (mPackages) {
20523            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20524            if (pir != null) {
20525                final Iterator<PreferredActivity> it = pir.filterIterator();
20526                while (it.hasNext()) {
20527                    final PreferredActivity pa = it.next();
20528                    if (packageName == null
20529                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
20530                                    && pa.mPref.mAlways)) {
20531                        if (outFilters != null) {
20532                            outFilters.add(new IntentFilter(pa));
20533                        }
20534                        if (outActivities != null) {
20535                            outActivities.add(pa.mPref.mComponent);
20536                        }
20537                    }
20538                }
20539            }
20540        }
20541
20542        return num;
20543    }
20544
20545    @Override
20546    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
20547            int userId) {
20548        int callingUid = Binder.getCallingUid();
20549        if (callingUid != Process.SYSTEM_UID) {
20550            throw new SecurityException(
20551                    "addPersistentPreferredActivity can only be run by the system");
20552        }
20553        if (filter.countActions() == 0) {
20554            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20555            return;
20556        }
20557        synchronized (mPackages) {
20558            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
20559                    ":");
20560            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20561            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
20562                    new PersistentPreferredActivity(filter, activity));
20563            scheduleWritePackageRestrictionsLocked(userId);
20564            postPreferredActivityChangedBroadcast(userId);
20565        }
20566    }
20567
20568    @Override
20569    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
20570        int callingUid = Binder.getCallingUid();
20571        if (callingUid != Process.SYSTEM_UID) {
20572            throw new SecurityException(
20573                    "clearPackagePersistentPreferredActivities can only be run by the system");
20574        }
20575        ArrayList<PersistentPreferredActivity> removed = null;
20576        boolean changed = false;
20577        synchronized (mPackages) {
20578            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
20579                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
20580                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
20581                        .valueAt(i);
20582                if (userId != thisUserId) {
20583                    continue;
20584                }
20585                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
20586                while (it.hasNext()) {
20587                    PersistentPreferredActivity ppa = it.next();
20588                    // Mark entry for removal only if it matches the package name.
20589                    if (ppa.mComponent.getPackageName().equals(packageName)) {
20590                        if (removed == null) {
20591                            removed = new ArrayList<PersistentPreferredActivity>();
20592                        }
20593                        removed.add(ppa);
20594                    }
20595                }
20596                if (removed != null) {
20597                    for (int j=0; j<removed.size(); j++) {
20598                        PersistentPreferredActivity ppa = removed.get(j);
20599                        ppir.removeFilter(ppa);
20600                    }
20601                    changed = true;
20602                }
20603            }
20604
20605            if (changed) {
20606                scheduleWritePackageRestrictionsLocked(userId);
20607                postPreferredActivityChangedBroadcast(userId);
20608            }
20609        }
20610    }
20611
20612    /**
20613     * Common machinery for picking apart a restored XML blob and passing
20614     * it to a caller-supplied functor to be applied to the running system.
20615     */
20616    private void restoreFromXml(XmlPullParser parser, int userId,
20617            String expectedStartTag, BlobXmlRestorer functor)
20618            throws IOException, XmlPullParserException {
20619        int type;
20620        while ((type = parser.next()) != XmlPullParser.START_TAG
20621                && type != XmlPullParser.END_DOCUMENT) {
20622        }
20623        if (type != XmlPullParser.START_TAG) {
20624            // oops didn't find a start tag?!
20625            if (DEBUG_BACKUP) {
20626                Slog.e(TAG, "Didn't find start tag during restore");
20627            }
20628            return;
20629        }
20630Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
20631        // this is supposed to be TAG_PREFERRED_BACKUP
20632        if (!expectedStartTag.equals(parser.getName())) {
20633            if (DEBUG_BACKUP) {
20634                Slog.e(TAG, "Found unexpected tag " + parser.getName());
20635            }
20636            return;
20637        }
20638
20639        // skip interfering stuff, then we're aligned with the backing implementation
20640        while ((type = parser.next()) == XmlPullParser.TEXT) { }
20641Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
20642        functor.apply(parser, userId);
20643    }
20644
20645    private interface BlobXmlRestorer {
20646        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
20647    }
20648
20649    /**
20650     * Non-Binder method, support for the backup/restore mechanism: write the
20651     * full set of preferred activities in its canonical XML format.  Returns the
20652     * XML output as a byte array, or null if there is none.
20653     */
20654    @Override
20655    public byte[] getPreferredActivityBackup(int userId) {
20656        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20657            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
20658        }
20659
20660        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20661        try {
20662            final XmlSerializer serializer = new FastXmlSerializer();
20663            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20664            serializer.startDocument(null, true);
20665            serializer.startTag(null, TAG_PREFERRED_BACKUP);
20666
20667            synchronized (mPackages) {
20668                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
20669            }
20670
20671            serializer.endTag(null, TAG_PREFERRED_BACKUP);
20672            serializer.endDocument();
20673            serializer.flush();
20674        } catch (Exception e) {
20675            if (DEBUG_BACKUP) {
20676                Slog.e(TAG, "Unable to write preferred activities for backup", e);
20677            }
20678            return null;
20679        }
20680
20681        return dataStream.toByteArray();
20682    }
20683
20684    @Override
20685    public void restorePreferredActivities(byte[] backup, int userId) {
20686        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20687            throw new SecurityException("Only the system may call restorePreferredActivities()");
20688        }
20689
20690        try {
20691            final XmlPullParser parser = Xml.newPullParser();
20692            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20693            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
20694                    new BlobXmlRestorer() {
20695                        @Override
20696                        public void apply(XmlPullParser parser, int userId)
20697                                throws XmlPullParserException, IOException {
20698                            synchronized (mPackages) {
20699                                mSettings.readPreferredActivitiesLPw(parser, userId);
20700                            }
20701                        }
20702                    } );
20703        } catch (Exception e) {
20704            if (DEBUG_BACKUP) {
20705                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20706            }
20707        }
20708    }
20709
20710    /**
20711     * Non-Binder method, support for the backup/restore mechanism: write the
20712     * default browser (etc) settings in its canonical XML format.  Returns the default
20713     * browser XML representation as a byte array, or null if there is none.
20714     */
20715    @Override
20716    public byte[] getDefaultAppsBackup(int userId) {
20717        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20718            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
20719        }
20720
20721        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20722        try {
20723            final XmlSerializer serializer = new FastXmlSerializer();
20724            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20725            serializer.startDocument(null, true);
20726            serializer.startTag(null, TAG_DEFAULT_APPS);
20727
20728            synchronized (mPackages) {
20729                mSettings.writeDefaultAppsLPr(serializer, userId);
20730            }
20731
20732            serializer.endTag(null, TAG_DEFAULT_APPS);
20733            serializer.endDocument();
20734            serializer.flush();
20735        } catch (Exception e) {
20736            if (DEBUG_BACKUP) {
20737                Slog.e(TAG, "Unable to write default apps for backup", e);
20738            }
20739            return null;
20740        }
20741
20742        return dataStream.toByteArray();
20743    }
20744
20745    @Override
20746    public void restoreDefaultApps(byte[] backup, int userId) {
20747        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20748            throw new SecurityException("Only the system may call restoreDefaultApps()");
20749        }
20750
20751        try {
20752            final XmlPullParser parser = Xml.newPullParser();
20753            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20754            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
20755                    new BlobXmlRestorer() {
20756                        @Override
20757                        public void apply(XmlPullParser parser, int userId)
20758                                throws XmlPullParserException, IOException {
20759                            synchronized (mPackages) {
20760                                mSettings.readDefaultAppsLPw(parser, userId);
20761                            }
20762                        }
20763                    } );
20764        } catch (Exception e) {
20765            if (DEBUG_BACKUP) {
20766                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
20767            }
20768        }
20769    }
20770
20771    @Override
20772    public byte[] getIntentFilterVerificationBackup(int userId) {
20773        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20774            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
20775        }
20776
20777        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20778        try {
20779            final XmlSerializer serializer = new FastXmlSerializer();
20780            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20781            serializer.startDocument(null, true);
20782            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
20783
20784            synchronized (mPackages) {
20785                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
20786            }
20787
20788            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
20789            serializer.endDocument();
20790            serializer.flush();
20791        } catch (Exception e) {
20792            if (DEBUG_BACKUP) {
20793                Slog.e(TAG, "Unable to write default apps for backup", e);
20794            }
20795            return null;
20796        }
20797
20798        return dataStream.toByteArray();
20799    }
20800
20801    @Override
20802    public void restoreIntentFilterVerification(byte[] backup, int userId) {
20803        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20804            throw new SecurityException("Only the system may call restorePreferredActivities()");
20805        }
20806
20807        try {
20808            final XmlPullParser parser = Xml.newPullParser();
20809            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20810            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
20811                    new BlobXmlRestorer() {
20812                        @Override
20813                        public void apply(XmlPullParser parser, int userId)
20814                                throws XmlPullParserException, IOException {
20815                            synchronized (mPackages) {
20816                                mSettings.readAllDomainVerificationsLPr(parser, userId);
20817                                mSettings.writeLPr();
20818                            }
20819                        }
20820                    } );
20821        } catch (Exception e) {
20822            if (DEBUG_BACKUP) {
20823                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20824            }
20825        }
20826    }
20827
20828    @Override
20829    public byte[] getPermissionGrantBackup(int userId) {
20830        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20831            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
20832        }
20833
20834        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20835        try {
20836            final XmlSerializer serializer = new FastXmlSerializer();
20837            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20838            serializer.startDocument(null, true);
20839            serializer.startTag(null, TAG_PERMISSION_BACKUP);
20840
20841            synchronized (mPackages) {
20842                serializeRuntimePermissionGrantsLPr(serializer, userId);
20843            }
20844
20845            serializer.endTag(null, TAG_PERMISSION_BACKUP);
20846            serializer.endDocument();
20847            serializer.flush();
20848        } catch (Exception e) {
20849            if (DEBUG_BACKUP) {
20850                Slog.e(TAG, "Unable to write default apps for backup", e);
20851            }
20852            return null;
20853        }
20854
20855        return dataStream.toByteArray();
20856    }
20857
20858    @Override
20859    public void restorePermissionGrants(byte[] backup, int userId) {
20860        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20861            throw new SecurityException("Only the system may call restorePermissionGrants()");
20862        }
20863
20864        try {
20865            final XmlPullParser parser = Xml.newPullParser();
20866            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20867            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
20868                    new BlobXmlRestorer() {
20869                        @Override
20870                        public void apply(XmlPullParser parser, int userId)
20871                                throws XmlPullParserException, IOException {
20872                            synchronized (mPackages) {
20873                                processRestoredPermissionGrantsLPr(parser, userId);
20874                            }
20875                        }
20876                    } );
20877        } catch (Exception e) {
20878            if (DEBUG_BACKUP) {
20879                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20880            }
20881        }
20882    }
20883
20884    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
20885            throws IOException {
20886        serializer.startTag(null, TAG_ALL_GRANTS);
20887
20888        final int N = mSettings.mPackages.size();
20889        for (int i = 0; i < N; i++) {
20890            final PackageSetting ps = mSettings.mPackages.valueAt(i);
20891            boolean pkgGrantsKnown = false;
20892
20893            PermissionsState packagePerms = ps.getPermissionsState();
20894
20895            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
20896                final int grantFlags = state.getFlags();
20897                // only look at grants that are not system/policy fixed
20898                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
20899                    final boolean isGranted = state.isGranted();
20900                    // And only back up the user-twiddled state bits
20901                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
20902                        final String packageName = mSettings.mPackages.keyAt(i);
20903                        if (!pkgGrantsKnown) {
20904                            serializer.startTag(null, TAG_GRANT);
20905                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
20906                            pkgGrantsKnown = true;
20907                        }
20908
20909                        final boolean userSet =
20910                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
20911                        final boolean userFixed =
20912                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
20913                        final boolean revoke =
20914                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
20915
20916                        serializer.startTag(null, TAG_PERMISSION);
20917                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
20918                        if (isGranted) {
20919                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
20920                        }
20921                        if (userSet) {
20922                            serializer.attribute(null, ATTR_USER_SET, "true");
20923                        }
20924                        if (userFixed) {
20925                            serializer.attribute(null, ATTR_USER_FIXED, "true");
20926                        }
20927                        if (revoke) {
20928                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
20929                        }
20930                        serializer.endTag(null, TAG_PERMISSION);
20931                    }
20932                }
20933            }
20934
20935            if (pkgGrantsKnown) {
20936                serializer.endTag(null, TAG_GRANT);
20937            }
20938        }
20939
20940        serializer.endTag(null, TAG_ALL_GRANTS);
20941    }
20942
20943    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
20944            throws XmlPullParserException, IOException {
20945        String pkgName = null;
20946        int outerDepth = parser.getDepth();
20947        int type;
20948        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
20949                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
20950            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
20951                continue;
20952            }
20953
20954            final String tagName = parser.getName();
20955            if (tagName.equals(TAG_GRANT)) {
20956                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
20957                if (DEBUG_BACKUP) {
20958                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
20959                }
20960            } else if (tagName.equals(TAG_PERMISSION)) {
20961
20962                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
20963                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
20964
20965                int newFlagSet = 0;
20966                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
20967                    newFlagSet |= FLAG_PERMISSION_USER_SET;
20968                }
20969                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
20970                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
20971                }
20972                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
20973                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
20974                }
20975                if (DEBUG_BACKUP) {
20976                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
20977                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
20978                }
20979                final PackageSetting ps = mSettings.mPackages.get(pkgName);
20980                if (ps != null) {
20981                    // Already installed so we apply the grant immediately
20982                    if (DEBUG_BACKUP) {
20983                        Slog.v(TAG, "        + already installed; applying");
20984                    }
20985                    PermissionsState perms = ps.getPermissionsState();
20986                    BasePermission bp = mSettings.mPermissions.get(permName);
20987                    if (bp != null) {
20988                        if (isGranted) {
20989                            perms.grantRuntimePermission(bp, userId);
20990                        }
20991                        if (newFlagSet != 0) {
20992                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
20993                        }
20994                    }
20995                } else {
20996                    // Need to wait for post-restore install to apply the grant
20997                    if (DEBUG_BACKUP) {
20998                        Slog.v(TAG, "        - not yet installed; saving for later");
20999                    }
21000                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
21001                            isGranted, newFlagSet, userId);
21002                }
21003            } else {
21004                PackageManagerService.reportSettingsProblem(Log.WARN,
21005                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
21006                XmlUtils.skipCurrentTag(parser);
21007            }
21008        }
21009
21010        scheduleWriteSettingsLocked();
21011        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
21012    }
21013
21014    @Override
21015    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
21016            int sourceUserId, int targetUserId, int flags) {
21017        mContext.enforceCallingOrSelfPermission(
21018                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
21019        int callingUid = Binder.getCallingUid();
21020        enforceOwnerRights(ownerPackage, callingUid);
21021        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
21022        if (intentFilter.countActions() == 0) {
21023            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
21024            return;
21025        }
21026        synchronized (mPackages) {
21027            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
21028                    ownerPackage, targetUserId, flags);
21029            CrossProfileIntentResolver resolver =
21030                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
21031            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
21032            // We have all those whose filter is equal. Now checking if the rest is equal as well.
21033            if (existing != null) {
21034                int size = existing.size();
21035                for (int i = 0; i < size; i++) {
21036                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
21037                        return;
21038                    }
21039                }
21040            }
21041            resolver.addFilter(newFilter);
21042            scheduleWritePackageRestrictionsLocked(sourceUserId);
21043        }
21044    }
21045
21046    @Override
21047    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
21048        mContext.enforceCallingOrSelfPermission(
21049                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
21050        final int callingUid = Binder.getCallingUid();
21051        enforceOwnerRights(ownerPackage, callingUid);
21052        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
21053        synchronized (mPackages) {
21054            CrossProfileIntentResolver resolver =
21055                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
21056            ArraySet<CrossProfileIntentFilter> set =
21057                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
21058            for (CrossProfileIntentFilter filter : set) {
21059                if (filter.getOwnerPackage().equals(ownerPackage)) {
21060                    resolver.removeFilter(filter);
21061                }
21062            }
21063            scheduleWritePackageRestrictionsLocked(sourceUserId);
21064        }
21065    }
21066
21067    // Enforcing that callingUid is owning pkg on userId
21068    private void enforceOwnerRights(String pkg, int callingUid) {
21069        // The system owns everything.
21070        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
21071            return;
21072        }
21073        final int callingUserId = UserHandle.getUserId(callingUid);
21074        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
21075        if (pi == null) {
21076            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
21077                    + callingUserId);
21078        }
21079        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
21080            throw new SecurityException("Calling uid " + callingUid
21081                    + " does not own package " + pkg);
21082        }
21083    }
21084
21085    @Override
21086    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
21087        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21088            return null;
21089        }
21090        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
21091    }
21092
21093    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
21094        UserManagerService ums = UserManagerService.getInstance();
21095        if (ums != null) {
21096            final UserInfo parent = ums.getProfileParent(userId);
21097            final int launcherUid = (parent != null) ? parent.id : userId;
21098            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
21099            if (launcherComponent != null) {
21100                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
21101                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
21102                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
21103                        .setPackage(launcherComponent.getPackageName());
21104                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
21105            }
21106        }
21107    }
21108
21109    /**
21110     * Report the 'Home' activity which is currently set as "always use this one". If non is set
21111     * then reports the most likely home activity or null if there are more than one.
21112     */
21113    private ComponentName getDefaultHomeActivity(int userId) {
21114        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
21115        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
21116        if (cn != null) {
21117            return cn;
21118        }
21119
21120        // Find the launcher with the highest priority and return that component if there are no
21121        // other home activity with the same priority.
21122        int lastPriority = Integer.MIN_VALUE;
21123        ComponentName lastComponent = null;
21124        final int size = allHomeCandidates.size();
21125        for (int i = 0; i < size; i++) {
21126            final ResolveInfo ri = allHomeCandidates.get(i);
21127            if (ri.priority > lastPriority) {
21128                lastComponent = ri.activityInfo.getComponentName();
21129                lastPriority = ri.priority;
21130            } else if (ri.priority == lastPriority) {
21131                // Two components found with same priority.
21132                lastComponent = null;
21133            }
21134        }
21135        return lastComponent;
21136    }
21137
21138    private Intent getHomeIntent() {
21139        Intent intent = new Intent(Intent.ACTION_MAIN);
21140        intent.addCategory(Intent.CATEGORY_HOME);
21141        intent.addCategory(Intent.CATEGORY_DEFAULT);
21142        return intent;
21143    }
21144
21145    private IntentFilter getHomeFilter() {
21146        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
21147        filter.addCategory(Intent.CATEGORY_HOME);
21148        filter.addCategory(Intent.CATEGORY_DEFAULT);
21149        return filter;
21150    }
21151
21152    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
21153            int userId) {
21154        Intent intent  = getHomeIntent();
21155        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
21156                PackageManager.GET_META_DATA, userId);
21157        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
21158                true, false, false, userId);
21159
21160        allHomeCandidates.clear();
21161        if (list != null) {
21162            for (ResolveInfo ri : list) {
21163                allHomeCandidates.add(ri);
21164            }
21165        }
21166        return (preferred == null || preferred.activityInfo == null)
21167                ? null
21168                : new ComponentName(preferred.activityInfo.packageName,
21169                        preferred.activityInfo.name);
21170    }
21171
21172    @Override
21173    public void setHomeActivity(ComponentName comp, int userId) {
21174        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21175            return;
21176        }
21177        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
21178        getHomeActivitiesAsUser(homeActivities, userId);
21179
21180        boolean found = false;
21181
21182        final int size = homeActivities.size();
21183        final ComponentName[] set = new ComponentName[size];
21184        for (int i = 0; i < size; i++) {
21185            final ResolveInfo candidate = homeActivities.get(i);
21186            final ActivityInfo info = candidate.activityInfo;
21187            final ComponentName activityName = new ComponentName(info.packageName, info.name);
21188            set[i] = activityName;
21189            if (!found && activityName.equals(comp)) {
21190                found = true;
21191            }
21192        }
21193        if (!found) {
21194            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
21195                    + userId);
21196        }
21197        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
21198                set, comp, userId);
21199    }
21200
21201    private @Nullable String getSetupWizardPackageName() {
21202        final Intent intent = new Intent(Intent.ACTION_MAIN);
21203        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
21204
21205        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21206                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21207                        | MATCH_DISABLED_COMPONENTS,
21208                UserHandle.myUserId());
21209        if (matches.size() == 1) {
21210            return matches.get(0).getComponentInfo().packageName;
21211        } else {
21212            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
21213                    + ": matches=" + matches);
21214            return null;
21215        }
21216    }
21217
21218    private @Nullable String getStorageManagerPackageName() {
21219        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
21220
21221        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21222                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21223                        | MATCH_DISABLED_COMPONENTS,
21224                UserHandle.myUserId());
21225        if (matches.size() == 1) {
21226            return matches.get(0).getComponentInfo().packageName;
21227        } else {
21228            Slog.e(TAG, "There should probably be exactly one storage manager; found "
21229                    + matches.size() + ": matches=" + matches);
21230            return null;
21231        }
21232    }
21233
21234    @Override
21235    public void setApplicationEnabledSetting(String appPackageName,
21236            int newState, int flags, int userId, String callingPackage) {
21237        if (!sUserManager.exists(userId)) return;
21238        if (callingPackage == null) {
21239            callingPackage = Integer.toString(Binder.getCallingUid());
21240        }
21241        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
21242    }
21243
21244    @Override
21245    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
21246        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
21247        synchronized (mPackages) {
21248            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
21249            if (pkgSetting != null) {
21250                pkgSetting.setUpdateAvailable(updateAvailable);
21251            }
21252        }
21253    }
21254
21255    @Override
21256    public void setComponentEnabledSetting(ComponentName componentName,
21257            int newState, int flags, int userId) {
21258        if (!sUserManager.exists(userId)) return;
21259        setEnabledSetting(componentName.getPackageName(),
21260                componentName.getClassName(), newState, flags, userId, null);
21261    }
21262
21263    private void setEnabledSetting(final String packageName, String className, int newState,
21264            final int flags, int userId, String callingPackage) {
21265        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
21266              || newState == COMPONENT_ENABLED_STATE_ENABLED
21267              || newState == COMPONENT_ENABLED_STATE_DISABLED
21268              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21269              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
21270            throw new IllegalArgumentException("Invalid new component state: "
21271                    + newState);
21272        }
21273        PackageSetting pkgSetting;
21274        final int callingUid = Binder.getCallingUid();
21275        final int permission;
21276        if (callingUid == Process.SYSTEM_UID) {
21277            permission = PackageManager.PERMISSION_GRANTED;
21278        } else {
21279            permission = mContext.checkCallingOrSelfPermission(
21280                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21281        }
21282        enforceCrossUserPermission(callingUid, userId,
21283                false /* requireFullPermission */, true /* checkShell */, "set enabled");
21284        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21285        boolean sendNow = false;
21286        boolean isApp = (className == null);
21287        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
21288        String componentName = isApp ? packageName : className;
21289        int packageUid = -1;
21290        ArrayList<String> components;
21291
21292        // reader
21293        synchronized (mPackages) {
21294            pkgSetting = mSettings.mPackages.get(packageName);
21295            if (pkgSetting == null) {
21296                if (!isCallerInstantApp) {
21297                    if (className == null) {
21298                        throw new IllegalArgumentException("Unknown package: " + packageName);
21299                    }
21300                    throw new IllegalArgumentException(
21301                            "Unknown component: " + packageName + "/" + className);
21302                } else {
21303                    // throw SecurityException to prevent leaking package information
21304                    throw new SecurityException(
21305                            "Attempt to change component state; "
21306                            + "pid=" + Binder.getCallingPid()
21307                            + ", uid=" + callingUid
21308                            + (className == null
21309                                    ? ", package=" + packageName
21310                                    : ", component=" + packageName + "/" + className));
21311                }
21312            }
21313        }
21314
21315        // Limit who can change which apps
21316        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
21317            // Don't allow apps that don't have permission to modify other apps
21318            if (!allowedByPermission
21319                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
21320                throw new SecurityException(
21321                        "Attempt to change component state; "
21322                        + "pid=" + Binder.getCallingPid()
21323                        + ", uid=" + callingUid
21324                        + (className == null
21325                                ? ", package=" + packageName
21326                                : ", component=" + packageName + "/" + className));
21327            }
21328            // Don't allow changing protected packages.
21329            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
21330                throw new SecurityException("Cannot disable a protected package: " + packageName);
21331            }
21332        }
21333
21334        synchronized (mPackages) {
21335            if (callingUid == Process.SHELL_UID
21336                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
21337                // Shell can only change whole packages between ENABLED and DISABLED_USER states
21338                // unless it is a test package.
21339                int oldState = pkgSetting.getEnabled(userId);
21340                if (className == null
21341                    &&
21342                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
21343                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
21344                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
21345                    &&
21346                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21347                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
21348                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
21349                    // ok
21350                } else {
21351                    throw new SecurityException(
21352                            "Shell cannot change component state for " + packageName + "/"
21353                            + className + " to " + newState);
21354                }
21355            }
21356            if (className == null) {
21357                // We're dealing with an application/package level state change
21358                if (pkgSetting.getEnabled(userId) == newState) {
21359                    // Nothing to do
21360                    return;
21361                }
21362                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
21363                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
21364                    // Don't care about who enables an app.
21365                    callingPackage = null;
21366                }
21367                pkgSetting.setEnabled(newState, userId, callingPackage);
21368                // pkgSetting.pkg.mSetEnabled = newState;
21369            } else {
21370                // We're dealing with a component level state change
21371                // First, verify that this is a valid class name.
21372                PackageParser.Package pkg = pkgSetting.pkg;
21373                if (pkg == null || !pkg.hasComponentClassName(className)) {
21374                    if (pkg != null &&
21375                            pkg.applicationInfo.targetSdkVersion >=
21376                                    Build.VERSION_CODES.JELLY_BEAN) {
21377                        throw new IllegalArgumentException("Component class " + className
21378                                + " does not exist in " + packageName);
21379                    } else {
21380                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
21381                                + className + " does not exist in " + packageName);
21382                    }
21383                }
21384                switch (newState) {
21385                case COMPONENT_ENABLED_STATE_ENABLED:
21386                    if (!pkgSetting.enableComponentLPw(className, userId)) {
21387                        return;
21388                    }
21389                    break;
21390                case COMPONENT_ENABLED_STATE_DISABLED:
21391                    if (!pkgSetting.disableComponentLPw(className, userId)) {
21392                        return;
21393                    }
21394                    break;
21395                case COMPONENT_ENABLED_STATE_DEFAULT:
21396                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
21397                        return;
21398                    }
21399                    break;
21400                default:
21401                    Slog.e(TAG, "Invalid new component state: " + newState);
21402                    return;
21403                }
21404            }
21405            scheduleWritePackageRestrictionsLocked(userId);
21406            updateSequenceNumberLP(pkgSetting, new int[] { userId });
21407            final long callingId = Binder.clearCallingIdentity();
21408            try {
21409                updateInstantAppInstallerLocked(packageName);
21410            } finally {
21411                Binder.restoreCallingIdentity(callingId);
21412            }
21413            components = mPendingBroadcasts.get(userId, packageName);
21414            final boolean newPackage = components == null;
21415            if (newPackage) {
21416                components = new ArrayList<String>();
21417            }
21418            if (!components.contains(componentName)) {
21419                components.add(componentName);
21420            }
21421            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
21422                sendNow = true;
21423                // Purge entry from pending broadcast list if another one exists already
21424                // since we are sending one right away.
21425                mPendingBroadcasts.remove(userId, packageName);
21426            } else {
21427                if (newPackage) {
21428                    mPendingBroadcasts.put(userId, packageName, components);
21429                }
21430                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
21431                    // Schedule a message
21432                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
21433                }
21434            }
21435        }
21436
21437        long callingId = Binder.clearCallingIdentity();
21438        try {
21439            if (sendNow) {
21440                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
21441                sendPackageChangedBroadcast(packageName,
21442                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
21443            }
21444        } finally {
21445            Binder.restoreCallingIdentity(callingId);
21446        }
21447    }
21448
21449    @Override
21450    public void flushPackageRestrictionsAsUser(int userId) {
21451        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21452            return;
21453        }
21454        if (!sUserManager.exists(userId)) {
21455            return;
21456        }
21457        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
21458                false /* checkShell */, "flushPackageRestrictions");
21459        synchronized (mPackages) {
21460            mSettings.writePackageRestrictionsLPr(userId);
21461            mDirtyUsers.remove(userId);
21462            if (mDirtyUsers.isEmpty()) {
21463                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
21464            }
21465        }
21466    }
21467
21468    private void sendPackageChangedBroadcast(String packageName,
21469            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
21470        if (DEBUG_INSTALL)
21471            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
21472                    + componentNames);
21473        Bundle extras = new Bundle(4);
21474        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
21475        String nameList[] = new String[componentNames.size()];
21476        componentNames.toArray(nameList);
21477        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
21478        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
21479        extras.putInt(Intent.EXTRA_UID, packageUid);
21480        // If this is not reporting a change of the overall package, then only send it
21481        // to registered receivers.  We don't want to launch a swath of apps for every
21482        // little component state change.
21483        final int flags = !componentNames.contains(packageName)
21484                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
21485        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
21486                new int[] {UserHandle.getUserId(packageUid)});
21487    }
21488
21489    @Override
21490    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
21491        if (!sUserManager.exists(userId)) return;
21492        final int callingUid = Binder.getCallingUid();
21493        if (getInstantAppPackageName(callingUid) != null) {
21494            return;
21495        }
21496        final int permission = mContext.checkCallingOrSelfPermission(
21497                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21498        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21499        enforceCrossUserPermission(callingUid, userId,
21500                true /* requireFullPermission */, true /* checkShell */, "stop package");
21501        // writer
21502        synchronized (mPackages) {
21503            final PackageSetting ps = mSettings.mPackages.get(packageName);
21504            if (!filterAppAccessLPr(ps, callingUid, userId)
21505                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
21506                            allowedByPermission, callingUid, userId)) {
21507                scheduleWritePackageRestrictionsLocked(userId);
21508            }
21509        }
21510    }
21511
21512    @Override
21513    public String getInstallerPackageName(String packageName) {
21514        final int callingUid = Binder.getCallingUid();
21515        if (getInstantAppPackageName(callingUid) != null) {
21516            return null;
21517        }
21518        // reader
21519        synchronized (mPackages) {
21520            final PackageSetting ps = mSettings.mPackages.get(packageName);
21521            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
21522                return null;
21523            }
21524            return mSettings.getInstallerPackageNameLPr(packageName);
21525        }
21526    }
21527
21528    public boolean isOrphaned(String packageName) {
21529        // reader
21530        synchronized (mPackages) {
21531            return mSettings.isOrphaned(packageName);
21532        }
21533    }
21534
21535    @Override
21536    public int getApplicationEnabledSetting(String packageName, int userId) {
21537        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
21538        int callingUid = Binder.getCallingUid();
21539        enforceCrossUserPermission(callingUid, userId,
21540                false /* requireFullPermission */, false /* checkShell */, "get enabled");
21541        // reader
21542        synchronized (mPackages) {
21543            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
21544                return COMPONENT_ENABLED_STATE_DISABLED;
21545            }
21546            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
21547        }
21548    }
21549
21550    @Override
21551    public int getComponentEnabledSetting(ComponentName component, int userId) {
21552        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
21553        int callingUid = Binder.getCallingUid();
21554        enforceCrossUserPermission(callingUid, userId,
21555                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
21556        synchronized (mPackages) {
21557            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
21558                    component, TYPE_UNKNOWN, userId)) {
21559                return COMPONENT_ENABLED_STATE_DISABLED;
21560            }
21561            return mSettings.getComponentEnabledSettingLPr(component, userId);
21562        }
21563    }
21564
21565    @Override
21566    public void enterSafeMode() {
21567        enforceSystemOrRoot("Only the system can request entering safe mode");
21568
21569        if (!mSystemReady) {
21570            mSafeMode = true;
21571        }
21572    }
21573
21574    @Override
21575    public void systemReady() {
21576        enforceSystemOrRoot("Only the system can claim the system is ready");
21577
21578        mSystemReady = true;
21579        final ContentResolver resolver = mContext.getContentResolver();
21580        ContentObserver co = new ContentObserver(mHandler) {
21581            @Override
21582            public void onChange(boolean selfChange) {
21583                mEphemeralAppsDisabled =
21584                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
21585                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
21586            }
21587        };
21588        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
21589                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
21590                false, co, UserHandle.USER_SYSTEM);
21591        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
21592                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
21593        co.onChange(true);
21594
21595        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
21596        // disabled after already being started.
21597        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
21598                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
21599
21600        // Read the compatibilty setting when the system is ready.
21601        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
21602                mContext.getContentResolver(),
21603                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
21604        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
21605        if (DEBUG_SETTINGS) {
21606            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
21607        }
21608
21609        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
21610
21611        synchronized (mPackages) {
21612            // Verify that all of the preferred activity components actually
21613            // exist.  It is possible for applications to be updated and at
21614            // that point remove a previously declared activity component that
21615            // had been set as a preferred activity.  We try to clean this up
21616            // the next time we encounter that preferred activity, but it is
21617            // possible for the user flow to never be able to return to that
21618            // situation so here we do a sanity check to make sure we haven't
21619            // left any junk around.
21620            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
21621            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21622                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21623                removed.clear();
21624                for (PreferredActivity pa : pir.filterSet()) {
21625                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
21626                        removed.add(pa);
21627                    }
21628                }
21629                if (removed.size() > 0) {
21630                    for (int r=0; r<removed.size(); r++) {
21631                        PreferredActivity pa = removed.get(r);
21632                        Slog.w(TAG, "Removing dangling preferred activity: "
21633                                + pa.mPref.mComponent);
21634                        pir.removeFilter(pa);
21635                    }
21636                    mSettings.writePackageRestrictionsLPr(
21637                            mSettings.mPreferredActivities.keyAt(i));
21638                }
21639            }
21640
21641            for (int userId : UserManagerService.getInstance().getUserIds()) {
21642                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
21643                    grantPermissionsUserIds = ArrayUtils.appendInt(
21644                            grantPermissionsUserIds, userId);
21645                }
21646            }
21647        }
21648        sUserManager.systemReady();
21649
21650        // If we upgraded grant all default permissions before kicking off.
21651        for (int userId : grantPermissionsUserIds) {
21652            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
21653        }
21654
21655        // If we did not grant default permissions, we preload from this the
21656        // default permission exceptions lazily to ensure we don't hit the
21657        // disk on a new user creation.
21658        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
21659            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
21660        }
21661
21662        // Kick off any messages waiting for system ready
21663        if (mPostSystemReadyMessages != null) {
21664            for (Message msg : mPostSystemReadyMessages) {
21665                msg.sendToTarget();
21666            }
21667            mPostSystemReadyMessages = null;
21668        }
21669
21670        // Watch for external volumes that come and go over time
21671        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21672        storage.registerListener(mStorageListener);
21673
21674        mInstallerService.systemReady();
21675        mPackageDexOptimizer.systemReady();
21676
21677        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
21678                StorageManagerInternal.class);
21679        StorageManagerInternal.addExternalStoragePolicy(
21680                new StorageManagerInternal.ExternalStorageMountPolicy() {
21681            @Override
21682            public int getMountMode(int uid, String packageName) {
21683                if (Process.isIsolated(uid)) {
21684                    return Zygote.MOUNT_EXTERNAL_NONE;
21685                }
21686                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
21687                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21688                }
21689                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21690                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21691                }
21692                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21693                    return Zygote.MOUNT_EXTERNAL_READ;
21694                }
21695                return Zygote.MOUNT_EXTERNAL_WRITE;
21696            }
21697
21698            @Override
21699            public boolean hasExternalStorage(int uid, String packageName) {
21700                return true;
21701            }
21702        });
21703
21704        // Now that we're mostly running, clean up stale users and apps
21705        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
21706        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
21707
21708        if (mPrivappPermissionsViolations != null) {
21709            Slog.wtf(TAG,"Signature|privileged permissions not in "
21710                    + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
21711            mPrivappPermissionsViolations = null;
21712        }
21713    }
21714
21715    public void waitForAppDataPrepared() {
21716        if (mPrepareAppDataFuture == null) {
21717            return;
21718        }
21719        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
21720        mPrepareAppDataFuture = null;
21721    }
21722
21723    @Override
21724    public boolean isSafeMode() {
21725        // allow instant applications
21726        return mSafeMode;
21727    }
21728
21729    @Override
21730    public boolean hasSystemUidErrors() {
21731        // allow instant applications
21732        return mHasSystemUidErrors;
21733    }
21734
21735    static String arrayToString(int[] array) {
21736        StringBuffer buf = new StringBuffer(128);
21737        buf.append('[');
21738        if (array != null) {
21739            for (int i=0; i<array.length; i++) {
21740                if (i > 0) buf.append(", ");
21741                buf.append(array[i]);
21742            }
21743        }
21744        buf.append(']');
21745        return buf.toString();
21746    }
21747
21748    static class DumpState {
21749        public static final int DUMP_LIBS = 1 << 0;
21750        public static final int DUMP_FEATURES = 1 << 1;
21751        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
21752        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
21753        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
21754        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
21755        public static final int DUMP_PERMISSIONS = 1 << 6;
21756        public static final int DUMP_PACKAGES = 1 << 7;
21757        public static final int DUMP_SHARED_USERS = 1 << 8;
21758        public static final int DUMP_MESSAGES = 1 << 9;
21759        public static final int DUMP_PROVIDERS = 1 << 10;
21760        public static final int DUMP_VERIFIERS = 1 << 11;
21761        public static final int DUMP_PREFERRED = 1 << 12;
21762        public static final int DUMP_PREFERRED_XML = 1 << 13;
21763        public static final int DUMP_KEYSETS = 1 << 14;
21764        public static final int DUMP_VERSION = 1 << 15;
21765        public static final int DUMP_INSTALLS = 1 << 16;
21766        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
21767        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
21768        public static final int DUMP_FROZEN = 1 << 19;
21769        public static final int DUMP_DEXOPT = 1 << 20;
21770        public static final int DUMP_COMPILER_STATS = 1 << 21;
21771        public static final int DUMP_CHANGES = 1 << 22;
21772
21773        public static final int OPTION_SHOW_FILTERS = 1 << 0;
21774
21775        private int mTypes;
21776
21777        private int mOptions;
21778
21779        private boolean mTitlePrinted;
21780
21781        private SharedUserSetting mSharedUser;
21782
21783        public boolean isDumping(int type) {
21784            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
21785                return true;
21786            }
21787
21788            return (mTypes & type) != 0;
21789        }
21790
21791        public void setDump(int type) {
21792            mTypes |= type;
21793        }
21794
21795        public boolean isOptionEnabled(int option) {
21796            return (mOptions & option) != 0;
21797        }
21798
21799        public void setOptionEnabled(int option) {
21800            mOptions |= option;
21801        }
21802
21803        public boolean onTitlePrinted() {
21804            final boolean printed = mTitlePrinted;
21805            mTitlePrinted = true;
21806            return printed;
21807        }
21808
21809        public boolean getTitlePrinted() {
21810            return mTitlePrinted;
21811        }
21812
21813        public void setTitlePrinted(boolean enabled) {
21814            mTitlePrinted = enabled;
21815        }
21816
21817        public SharedUserSetting getSharedUser() {
21818            return mSharedUser;
21819        }
21820
21821        public void setSharedUser(SharedUserSetting user) {
21822            mSharedUser = user;
21823        }
21824    }
21825
21826    @Override
21827    public void onShellCommand(FileDescriptor in, FileDescriptor out,
21828            FileDescriptor err, String[] args, ShellCallback callback,
21829            ResultReceiver resultReceiver) {
21830        (new PackageManagerShellCommand(this)).exec(
21831                this, in, out, err, args, callback, resultReceiver);
21832    }
21833
21834    @Override
21835    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
21836        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
21837
21838        DumpState dumpState = new DumpState();
21839        boolean fullPreferred = false;
21840        boolean checkin = false;
21841
21842        String packageName = null;
21843        ArraySet<String> permissionNames = null;
21844
21845        int opti = 0;
21846        while (opti < args.length) {
21847            String opt = args[opti];
21848            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
21849                break;
21850            }
21851            opti++;
21852
21853            if ("-a".equals(opt)) {
21854                // Right now we only know how to print all.
21855            } else if ("-h".equals(opt)) {
21856                pw.println("Package manager dump options:");
21857                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
21858                pw.println("    --checkin: dump for a checkin");
21859                pw.println("    -f: print details of intent filters");
21860                pw.println("    -h: print this help");
21861                pw.println("  cmd may be one of:");
21862                pw.println("    l[ibraries]: list known shared libraries");
21863                pw.println("    f[eatures]: list device features");
21864                pw.println("    k[eysets]: print known keysets");
21865                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
21866                pw.println("    perm[issions]: dump permissions");
21867                pw.println("    permission [name ...]: dump declaration and use of given permission");
21868                pw.println("    pref[erred]: print preferred package settings");
21869                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
21870                pw.println("    prov[iders]: dump content providers");
21871                pw.println("    p[ackages]: dump installed packages");
21872                pw.println("    s[hared-users]: dump shared user IDs");
21873                pw.println("    m[essages]: print collected runtime messages");
21874                pw.println("    v[erifiers]: print package verifier info");
21875                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
21876                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
21877                pw.println("    version: print database version info");
21878                pw.println("    write: write current settings now");
21879                pw.println("    installs: details about install sessions");
21880                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
21881                pw.println("    dexopt: dump dexopt state");
21882                pw.println("    compiler-stats: dump compiler statistics");
21883                pw.println("    enabled-overlays: dump list of enabled overlay packages");
21884                pw.println("    <package.name>: info about given package");
21885                return;
21886            } else if ("--checkin".equals(opt)) {
21887                checkin = true;
21888            } else if ("-f".equals(opt)) {
21889                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21890            } else if ("--proto".equals(opt)) {
21891                dumpProto(fd);
21892                return;
21893            } else {
21894                pw.println("Unknown argument: " + opt + "; use -h for help");
21895            }
21896        }
21897
21898        // Is the caller requesting to dump a particular piece of data?
21899        if (opti < args.length) {
21900            String cmd = args[opti];
21901            opti++;
21902            // Is this a package name?
21903            if ("android".equals(cmd) || cmd.contains(".")) {
21904                packageName = cmd;
21905                // When dumping a single package, we always dump all of its
21906                // filter information since the amount of data will be reasonable.
21907                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21908            } else if ("check-permission".equals(cmd)) {
21909                if (opti >= args.length) {
21910                    pw.println("Error: check-permission missing permission argument");
21911                    return;
21912                }
21913                String perm = args[opti];
21914                opti++;
21915                if (opti >= args.length) {
21916                    pw.println("Error: check-permission missing package argument");
21917                    return;
21918                }
21919
21920                String pkg = args[opti];
21921                opti++;
21922                int user = UserHandle.getUserId(Binder.getCallingUid());
21923                if (opti < args.length) {
21924                    try {
21925                        user = Integer.parseInt(args[opti]);
21926                    } catch (NumberFormatException e) {
21927                        pw.println("Error: check-permission user argument is not a number: "
21928                                + args[opti]);
21929                        return;
21930                    }
21931                }
21932
21933                // Normalize package name to handle renamed packages and static libs
21934                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
21935
21936                pw.println(checkPermission(perm, pkg, user));
21937                return;
21938            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
21939                dumpState.setDump(DumpState.DUMP_LIBS);
21940            } else if ("f".equals(cmd) || "features".equals(cmd)) {
21941                dumpState.setDump(DumpState.DUMP_FEATURES);
21942            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
21943                if (opti >= args.length) {
21944                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
21945                            | DumpState.DUMP_SERVICE_RESOLVERS
21946                            | DumpState.DUMP_RECEIVER_RESOLVERS
21947                            | DumpState.DUMP_CONTENT_RESOLVERS);
21948                } else {
21949                    while (opti < args.length) {
21950                        String name = args[opti];
21951                        if ("a".equals(name) || "activity".equals(name)) {
21952                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
21953                        } else if ("s".equals(name) || "service".equals(name)) {
21954                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
21955                        } else if ("r".equals(name) || "receiver".equals(name)) {
21956                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
21957                        } else if ("c".equals(name) || "content".equals(name)) {
21958                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
21959                        } else {
21960                            pw.println("Error: unknown resolver table type: " + name);
21961                            return;
21962                        }
21963                        opti++;
21964                    }
21965                }
21966            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
21967                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
21968            } else if ("permission".equals(cmd)) {
21969                if (opti >= args.length) {
21970                    pw.println("Error: permission requires permission name");
21971                    return;
21972                }
21973                permissionNames = new ArraySet<>();
21974                while (opti < args.length) {
21975                    permissionNames.add(args[opti]);
21976                    opti++;
21977                }
21978                dumpState.setDump(DumpState.DUMP_PERMISSIONS
21979                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
21980            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
21981                dumpState.setDump(DumpState.DUMP_PREFERRED);
21982            } else if ("preferred-xml".equals(cmd)) {
21983                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
21984                if (opti < args.length && "--full".equals(args[opti])) {
21985                    fullPreferred = true;
21986                    opti++;
21987                }
21988            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
21989                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
21990            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
21991                dumpState.setDump(DumpState.DUMP_PACKAGES);
21992            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
21993                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
21994            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
21995                dumpState.setDump(DumpState.DUMP_PROVIDERS);
21996            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
21997                dumpState.setDump(DumpState.DUMP_MESSAGES);
21998            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
21999                dumpState.setDump(DumpState.DUMP_VERIFIERS);
22000            } else if ("i".equals(cmd) || "ifv".equals(cmd)
22001                    || "intent-filter-verifiers".equals(cmd)) {
22002                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
22003            } else if ("version".equals(cmd)) {
22004                dumpState.setDump(DumpState.DUMP_VERSION);
22005            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
22006                dumpState.setDump(DumpState.DUMP_KEYSETS);
22007            } else if ("installs".equals(cmd)) {
22008                dumpState.setDump(DumpState.DUMP_INSTALLS);
22009            } else if ("frozen".equals(cmd)) {
22010                dumpState.setDump(DumpState.DUMP_FROZEN);
22011            } else if ("dexopt".equals(cmd)) {
22012                dumpState.setDump(DumpState.DUMP_DEXOPT);
22013            } else if ("compiler-stats".equals(cmd)) {
22014                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
22015            } else if ("changes".equals(cmd)) {
22016                dumpState.setDump(DumpState.DUMP_CHANGES);
22017            } else if ("write".equals(cmd)) {
22018                synchronized (mPackages) {
22019                    mSettings.writeLPr();
22020                    pw.println("Settings written.");
22021                    return;
22022                }
22023            }
22024        }
22025
22026        if (checkin) {
22027            pw.println("vers,1");
22028        }
22029
22030        // reader
22031        synchronized (mPackages) {
22032            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
22033                if (!checkin) {
22034                    if (dumpState.onTitlePrinted())
22035                        pw.println();
22036                    pw.println("Database versions:");
22037                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
22038                }
22039            }
22040
22041            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
22042                if (!checkin) {
22043                    if (dumpState.onTitlePrinted())
22044                        pw.println();
22045                    pw.println("Verifiers:");
22046                    pw.print("  Required: ");
22047                    pw.print(mRequiredVerifierPackage);
22048                    pw.print(" (uid=");
22049                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
22050                            UserHandle.USER_SYSTEM));
22051                    pw.println(")");
22052                } else if (mRequiredVerifierPackage != null) {
22053                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
22054                    pw.print(",");
22055                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
22056                            UserHandle.USER_SYSTEM));
22057                }
22058            }
22059
22060            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
22061                    packageName == null) {
22062                if (mIntentFilterVerifierComponent != null) {
22063                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
22064                    if (!checkin) {
22065                        if (dumpState.onTitlePrinted())
22066                            pw.println();
22067                        pw.println("Intent Filter Verifier:");
22068                        pw.print("  Using: ");
22069                        pw.print(verifierPackageName);
22070                        pw.print(" (uid=");
22071                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
22072                                UserHandle.USER_SYSTEM));
22073                        pw.println(")");
22074                    } else if (verifierPackageName != null) {
22075                        pw.print("ifv,"); pw.print(verifierPackageName);
22076                        pw.print(",");
22077                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
22078                                UserHandle.USER_SYSTEM));
22079                    }
22080                } else {
22081                    pw.println();
22082                    pw.println("No Intent Filter Verifier available!");
22083                }
22084            }
22085
22086            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
22087                boolean printedHeader = false;
22088                final Iterator<String> it = mSharedLibraries.keySet().iterator();
22089                while (it.hasNext()) {
22090                    String libName = it.next();
22091                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
22092                    if (versionedLib == null) {
22093                        continue;
22094                    }
22095                    final int versionCount = versionedLib.size();
22096                    for (int i = 0; i < versionCount; i++) {
22097                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
22098                        if (!checkin) {
22099                            if (!printedHeader) {
22100                                if (dumpState.onTitlePrinted())
22101                                    pw.println();
22102                                pw.println("Libraries:");
22103                                printedHeader = true;
22104                            }
22105                            pw.print("  ");
22106                        } else {
22107                            pw.print("lib,");
22108                        }
22109                        pw.print(libEntry.info.getName());
22110                        if (libEntry.info.isStatic()) {
22111                            pw.print(" version=" + libEntry.info.getVersion());
22112                        }
22113                        if (!checkin) {
22114                            pw.print(" -> ");
22115                        }
22116                        if (libEntry.path != null) {
22117                            pw.print(" (jar) ");
22118                            pw.print(libEntry.path);
22119                        } else {
22120                            pw.print(" (apk) ");
22121                            pw.print(libEntry.apk);
22122                        }
22123                        pw.println();
22124                    }
22125                }
22126            }
22127
22128            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
22129                if (dumpState.onTitlePrinted())
22130                    pw.println();
22131                if (!checkin) {
22132                    pw.println("Features:");
22133                }
22134
22135                synchronized (mAvailableFeatures) {
22136                    for (FeatureInfo feat : mAvailableFeatures.values()) {
22137                        if (checkin) {
22138                            pw.print("feat,");
22139                            pw.print(feat.name);
22140                            pw.print(",");
22141                            pw.println(feat.version);
22142                        } else {
22143                            pw.print("  ");
22144                            pw.print(feat.name);
22145                            if (feat.version > 0) {
22146                                pw.print(" version=");
22147                                pw.print(feat.version);
22148                            }
22149                            pw.println();
22150                        }
22151                    }
22152                }
22153            }
22154
22155            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
22156                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
22157                        : "Activity Resolver Table:", "  ", packageName,
22158                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22159                    dumpState.setTitlePrinted(true);
22160                }
22161            }
22162            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
22163                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
22164                        : "Receiver Resolver Table:", "  ", packageName,
22165                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22166                    dumpState.setTitlePrinted(true);
22167                }
22168            }
22169            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
22170                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
22171                        : "Service Resolver Table:", "  ", packageName,
22172                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22173                    dumpState.setTitlePrinted(true);
22174                }
22175            }
22176            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
22177                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
22178                        : "Provider Resolver Table:", "  ", packageName,
22179                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22180                    dumpState.setTitlePrinted(true);
22181                }
22182            }
22183
22184            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
22185                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
22186                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
22187                    int user = mSettings.mPreferredActivities.keyAt(i);
22188                    if (pir.dump(pw,
22189                            dumpState.getTitlePrinted()
22190                                ? "\nPreferred Activities User " + user + ":"
22191                                : "Preferred Activities User " + user + ":", "  ",
22192                            packageName, true, false)) {
22193                        dumpState.setTitlePrinted(true);
22194                    }
22195                }
22196            }
22197
22198            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
22199                pw.flush();
22200                FileOutputStream fout = new FileOutputStream(fd);
22201                BufferedOutputStream str = new BufferedOutputStream(fout);
22202                XmlSerializer serializer = new FastXmlSerializer();
22203                try {
22204                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
22205                    serializer.startDocument(null, true);
22206                    serializer.setFeature(
22207                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
22208                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
22209                    serializer.endDocument();
22210                    serializer.flush();
22211                } catch (IllegalArgumentException e) {
22212                    pw.println("Failed writing: " + e);
22213                } catch (IllegalStateException e) {
22214                    pw.println("Failed writing: " + e);
22215                } catch (IOException e) {
22216                    pw.println("Failed writing: " + e);
22217                }
22218            }
22219
22220            if (!checkin
22221                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
22222                    && packageName == null) {
22223                pw.println();
22224                int count = mSettings.mPackages.size();
22225                if (count == 0) {
22226                    pw.println("No applications!");
22227                    pw.println();
22228                } else {
22229                    final String prefix = "  ";
22230                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
22231                    if (allPackageSettings.size() == 0) {
22232                        pw.println("No domain preferred apps!");
22233                        pw.println();
22234                    } else {
22235                        pw.println("App verification status:");
22236                        pw.println();
22237                        count = 0;
22238                        for (PackageSetting ps : allPackageSettings) {
22239                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
22240                            if (ivi == null || ivi.getPackageName() == null) continue;
22241                            pw.println(prefix + "Package: " + ivi.getPackageName());
22242                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
22243                            pw.println(prefix + "Status:  " + ivi.getStatusString());
22244                            pw.println();
22245                            count++;
22246                        }
22247                        if (count == 0) {
22248                            pw.println(prefix + "No app verification established.");
22249                            pw.println();
22250                        }
22251                        for (int userId : sUserManager.getUserIds()) {
22252                            pw.println("App linkages for user " + userId + ":");
22253                            pw.println();
22254                            count = 0;
22255                            for (PackageSetting ps : allPackageSettings) {
22256                                final long status = ps.getDomainVerificationStatusForUser(userId);
22257                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
22258                                        && !DEBUG_DOMAIN_VERIFICATION) {
22259                                    continue;
22260                                }
22261                                pw.println(prefix + "Package: " + ps.name);
22262                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
22263                                String statusStr = IntentFilterVerificationInfo.
22264                                        getStatusStringFromValue(status);
22265                                pw.println(prefix + "Status:  " + statusStr);
22266                                pw.println();
22267                                count++;
22268                            }
22269                            if (count == 0) {
22270                                pw.println(prefix + "No configured app linkages.");
22271                                pw.println();
22272                            }
22273                        }
22274                    }
22275                }
22276            }
22277
22278            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
22279                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
22280                if (packageName == null && permissionNames == null) {
22281                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
22282                        if (iperm == 0) {
22283                            if (dumpState.onTitlePrinted())
22284                                pw.println();
22285                            pw.println("AppOp Permissions:");
22286                        }
22287                        pw.print("  AppOp Permission ");
22288                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
22289                        pw.println(":");
22290                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
22291                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
22292                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
22293                        }
22294                    }
22295                }
22296            }
22297
22298            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
22299                boolean printedSomething = false;
22300                for (PackageParser.Provider p : mProviders.mProviders.values()) {
22301                    if (packageName != null && !packageName.equals(p.info.packageName)) {
22302                        continue;
22303                    }
22304                    if (!printedSomething) {
22305                        if (dumpState.onTitlePrinted())
22306                            pw.println();
22307                        pw.println("Registered ContentProviders:");
22308                        printedSomething = true;
22309                    }
22310                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
22311                    pw.print("    "); pw.println(p.toString());
22312                }
22313                printedSomething = false;
22314                for (Map.Entry<String, PackageParser.Provider> entry :
22315                        mProvidersByAuthority.entrySet()) {
22316                    PackageParser.Provider p = entry.getValue();
22317                    if (packageName != null && !packageName.equals(p.info.packageName)) {
22318                        continue;
22319                    }
22320                    if (!printedSomething) {
22321                        if (dumpState.onTitlePrinted())
22322                            pw.println();
22323                        pw.println("ContentProvider Authorities:");
22324                        printedSomething = true;
22325                    }
22326                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
22327                    pw.print("    "); pw.println(p.toString());
22328                    if (p.info != null && p.info.applicationInfo != null) {
22329                        final String appInfo = p.info.applicationInfo.toString();
22330                        pw.print("      applicationInfo="); pw.println(appInfo);
22331                    }
22332                }
22333            }
22334
22335            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
22336                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
22337            }
22338
22339            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
22340                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
22341            }
22342
22343            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
22344                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
22345            }
22346
22347            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
22348                if (dumpState.onTitlePrinted()) pw.println();
22349                pw.println("Package Changes:");
22350                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
22351                final int K = mChangedPackages.size();
22352                for (int i = 0; i < K; i++) {
22353                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
22354                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
22355                    final int N = changes.size();
22356                    if (N == 0) {
22357                        pw.print("    "); pw.println("No packages changed");
22358                    } else {
22359                        for (int j = 0; j < N; j++) {
22360                            final String pkgName = changes.valueAt(j);
22361                            final int sequenceNumber = changes.keyAt(j);
22362                            pw.print("    ");
22363                            pw.print("seq=");
22364                            pw.print(sequenceNumber);
22365                            pw.print(", package=");
22366                            pw.println(pkgName);
22367                        }
22368                    }
22369                }
22370            }
22371
22372            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
22373                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
22374            }
22375
22376            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
22377                // XXX should handle packageName != null by dumping only install data that
22378                // the given package is involved with.
22379                if (dumpState.onTitlePrinted()) pw.println();
22380
22381                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22382                ipw.println();
22383                ipw.println("Frozen packages:");
22384                ipw.increaseIndent();
22385                if (mFrozenPackages.size() == 0) {
22386                    ipw.println("(none)");
22387                } else {
22388                    for (int i = 0; i < mFrozenPackages.size(); i++) {
22389                        ipw.println(mFrozenPackages.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    }
23112
23113    private void unloadPrivatePackages(final VolumeInfo vol) {
23114        mHandler.post(new Runnable() {
23115            @Override
23116            public void run() {
23117                unloadPrivatePackagesInner(vol);
23118            }
23119        });
23120    }
23121
23122    private void unloadPrivatePackagesInner(VolumeInfo vol) {
23123        final String volumeUuid = vol.fsUuid;
23124        if (TextUtils.isEmpty(volumeUuid)) {
23125            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
23126            return;
23127        }
23128
23129        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
23130        synchronized (mInstallLock) {
23131        synchronized (mPackages) {
23132            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
23133            for (PackageSetting ps : packages) {
23134                if (ps.pkg == null) continue;
23135
23136                final ApplicationInfo info = ps.pkg.applicationInfo;
23137                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
23138                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
23139
23140                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
23141                        "unloadPrivatePackagesInner")) {
23142                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
23143                            false, null)) {
23144                        unloaded.add(info);
23145                    } else {
23146                        Slog.w(TAG, "Failed to unload " + ps.codePath);
23147                    }
23148                }
23149
23150                // Try very hard to release any references to this package
23151                // so we don't risk the system server being killed due to
23152                // open FDs
23153                AttributeCache.instance().removePackage(ps.name);
23154            }
23155
23156            mSettings.writeLPr();
23157        }
23158        }
23159
23160        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
23161        sendResourcesChangedBroadcast(false, false, unloaded, null);
23162
23163        // Try very hard to release any references to this path so we don't risk
23164        // the system server being killed due to open FDs
23165        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
23166
23167        for (int i = 0; i < 3; i++) {
23168            System.gc();
23169            System.runFinalization();
23170        }
23171    }
23172
23173    private void assertPackageKnown(String volumeUuid, String packageName)
23174            throws PackageManagerException {
23175        synchronized (mPackages) {
23176            // Normalize package name to handle renamed packages
23177            packageName = normalizePackageNameLPr(packageName);
23178
23179            final PackageSetting ps = mSettings.mPackages.get(packageName);
23180            if (ps == null) {
23181                throw new PackageManagerException("Package " + packageName + " is unknown");
23182            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23183                throw new PackageManagerException(
23184                        "Package " + packageName + " found on unknown volume " + volumeUuid
23185                                + "; expected volume " + ps.volumeUuid);
23186            }
23187        }
23188    }
23189
23190    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
23191            throws PackageManagerException {
23192        synchronized (mPackages) {
23193            // Normalize package name to handle renamed packages
23194            packageName = normalizePackageNameLPr(packageName);
23195
23196            final PackageSetting ps = mSettings.mPackages.get(packageName);
23197            if (ps == null) {
23198                throw new PackageManagerException("Package " + packageName + " is unknown");
23199            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23200                throw new PackageManagerException(
23201                        "Package " + packageName + " found on unknown volume " + volumeUuid
23202                                + "; expected volume " + ps.volumeUuid);
23203            } else if (!ps.getInstalled(userId)) {
23204                throw new PackageManagerException(
23205                        "Package " + packageName + " not installed for user " + userId);
23206            }
23207        }
23208    }
23209
23210    private List<String> collectAbsoluteCodePaths() {
23211        synchronized (mPackages) {
23212            List<String> codePaths = new ArrayList<>();
23213            final int packageCount = mSettings.mPackages.size();
23214            for (int i = 0; i < packageCount; i++) {
23215                final PackageSetting ps = mSettings.mPackages.valueAt(i);
23216                codePaths.add(ps.codePath.getAbsolutePath());
23217            }
23218            return codePaths;
23219        }
23220    }
23221
23222    /**
23223     * Examine all apps present on given mounted volume, and destroy apps that
23224     * aren't expected, either due to uninstallation or reinstallation on
23225     * another volume.
23226     */
23227    private void reconcileApps(String volumeUuid) {
23228        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
23229        List<File> filesToDelete = null;
23230
23231        final File[] files = FileUtils.listFilesOrEmpty(
23232                Environment.getDataAppDirectory(volumeUuid));
23233        for (File file : files) {
23234            final boolean isPackage = (isApkFile(file) || file.isDirectory())
23235                    && !PackageInstallerService.isStageName(file.getName());
23236            if (!isPackage) {
23237                // Ignore entries which are not packages
23238                continue;
23239            }
23240
23241            String absolutePath = file.getAbsolutePath();
23242
23243            boolean pathValid = false;
23244            final int absoluteCodePathCount = absoluteCodePaths.size();
23245            for (int i = 0; i < absoluteCodePathCount; i++) {
23246                String absoluteCodePath = absoluteCodePaths.get(i);
23247                if (absolutePath.startsWith(absoluteCodePath)) {
23248                    pathValid = true;
23249                    break;
23250                }
23251            }
23252
23253            if (!pathValid) {
23254                if (filesToDelete == null) {
23255                    filesToDelete = new ArrayList<>();
23256                }
23257                filesToDelete.add(file);
23258            }
23259        }
23260
23261        if (filesToDelete != null) {
23262            final int fileToDeleteCount = filesToDelete.size();
23263            for (int i = 0; i < fileToDeleteCount; i++) {
23264                File fileToDelete = filesToDelete.get(i);
23265                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
23266                synchronized (mInstallLock) {
23267                    removeCodePathLI(fileToDelete);
23268                }
23269            }
23270        }
23271    }
23272
23273    /**
23274     * Reconcile all app data for the given user.
23275     * <p>
23276     * Verifies that directories exist and that ownership and labeling is
23277     * correct for all installed apps on all mounted volumes.
23278     */
23279    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
23280        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23281        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
23282            final String volumeUuid = vol.getFsUuid();
23283            synchronized (mInstallLock) {
23284                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
23285            }
23286        }
23287    }
23288
23289    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23290            boolean migrateAppData) {
23291        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
23292    }
23293
23294    /**
23295     * Reconcile all app data on given mounted volume.
23296     * <p>
23297     * Destroys app data that isn't expected, either due to uninstallation or
23298     * reinstallation on another volume.
23299     * <p>
23300     * Verifies that directories exist and that ownership and labeling is
23301     * correct for all installed apps.
23302     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
23303     */
23304    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23305            boolean migrateAppData, boolean onlyCoreApps) {
23306        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
23307                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
23308        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
23309
23310        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
23311        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
23312
23313        // First look for stale data that doesn't belong, and check if things
23314        // have changed since we did our last restorecon
23315        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
23316            if (StorageManager.isFileEncryptedNativeOrEmulated()
23317                    && !StorageManager.isUserKeyUnlocked(userId)) {
23318                throw new RuntimeException(
23319                        "Yikes, someone asked us to reconcile CE storage while " + userId
23320                                + " was still locked; this would have caused massive data loss!");
23321            }
23322
23323            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
23324            for (File file : files) {
23325                final String packageName = file.getName();
23326                try {
23327                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
23328                } catch (PackageManagerException e) {
23329                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
23330                    try {
23331                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
23332                                StorageManager.FLAG_STORAGE_CE, 0);
23333                    } catch (InstallerException e2) {
23334                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
23335                    }
23336                }
23337            }
23338        }
23339        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
23340            final File[] files = FileUtils.listFilesOrEmpty(deDir);
23341            for (File file : files) {
23342                final String packageName = file.getName();
23343                try {
23344                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
23345                } catch (PackageManagerException e) {
23346                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
23347                    try {
23348                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
23349                                StorageManager.FLAG_STORAGE_DE, 0);
23350                    } catch (InstallerException e2) {
23351                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
23352                    }
23353                }
23354            }
23355        }
23356
23357        // Ensure that data directories are ready to roll for all packages
23358        // installed for this volume and user
23359        final List<PackageSetting> packages;
23360        synchronized (mPackages) {
23361            packages = mSettings.getVolumePackagesLPr(volumeUuid);
23362        }
23363        int preparedCount = 0;
23364        for (PackageSetting ps : packages) {
23365            final String packageName = ps.name;
23366            if (ps.pkg == null) {
23367                Slog.w(TAG, "Odd, missing scanned package " + packageName);
23368                // TODO: might be due to legacy ASEC apps; we should circle back
23369                // and reconcile again once they're scanned
23370                continue;
23371            }
23372            // Skip non-core apps if requested
23373            if (onlyCoreApps && !ps.pkg.coreApp) {
23374                result.add(packageName);
23375                continue;
23376            }
23377
23378            if (ps.getInstalled(userId)) {
23379                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
23380                preparedCount++;
23381            }
23382        }
23383
23384        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
23385        return result;
23386    }
23387
23388    /**
23389     * Prepare app data for the given app just after it was installed or
23390     * upgraded. This method carefully only touches users that it's installed
23391     * for, and it forces a restorecon to handle any seinfo changes.
23392     * <p>
23393     * Verifies that directories exist and that ownership and labeling is
23394     * correct for all installed apps. If there is an ownership mismatch, it
23395     * will try recovering system apps by wiping data; third-party app data is
23396     * left intact.
23397     * <p>
23398     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
23399     */
23400    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
23401        final PackageSetting ps;
23402        synchronized (mPackages) {
23403            ps = mSettings.mPackages.get(pkg.packageName);
23404            mSettings.writeKernelMappingLPr(ps);
23405        }
23406
23407        final UserManager um = mContext.getSystemService(UserManager.class);
23408        UserManagerInternal umInternal = getUserManagerInternal();
23409        for (UserInfo user : um.getUsers()) {
23410            final int flags;
23411            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
23412                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
23413            } else if (umInternal.isUserRunning(user.id)) {
23414                flags = StorageManager.FLAG_STORAGE_DE;
23415            } else {
23416                continue;
23417            }
23418
23419            if (ps.getInstalled(user.id)) {
23420                // TODO: when user data is locked, mark that we're still dirty
23421                prepareAppDataLIF(pkg, user.id, flags);
23422            }
23423        }
23424    }
23425
23426    /**
23427     * Prepare app data for the given app.
23428     * <p>
23429     * Verifies that directories exist and that ownership and labeling is
23430     * correct for all installed apps. If there is an ownership mismatch, this
23431     * will try recovering system apps by wiping data; third-party app data is
23432     * left intact.
23433     */
23434    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
23435        if (pkg == null) {
23436            Slog.wtf(TAG, "Package was null!", new Throwable());
23437            return;
23438        }
23439        prepareAppDataLeafLIF(pkg, userId, flags);
23440        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
23441        for (int i = 0; i < childCount; i++) {
23442            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
23443        }
23444    }
23445
23446    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
23447            boolean maybeMigrateAppData) {
23448        prepareAppDataLIF(pkg, userId, flags);
23449
23450        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
23451            // We may have just shuffled around app data directories, so
23452            // prepare them one more time
23453            prepareAppDataLIF(pkg, userId, flags);
23454        }
23455    }
23456
23457    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
23458        if (DEBUG_APP_DATA) {
23459            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
23460                    + Integer.toHexString(flags));
23461        }
23462
23463        final String volumeUuid = pkg.volumeUuid;
23464        final String packageName = pkg.packageName;
23465        final ApplicationInfo app = pkg.applicationInfo;
23466        final int appId = UserHandle.getAppId(app.uid);
23467
23468        Preconditions.checkNotNull(app.seInfo);
23469
23470        long ceDataInode = -1;
23471        try {
23472            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
23473                    appId, app.seInfo, app.targetSdkVersion);
23474        } catch (InstallerException e) {
23475            if (app.isSystemApp()) {
23476                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
23477                        + ", but trying to recover: " + e);
23478                destroyAppDataLeafLIF(pkg, userId, flags);
23479                try {
23480                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
23481                            appId, app.seInfo, app.targetSdkVersion);
23482                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
23483                } catch (InstallerException e2) {
23484                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
23485                }
23486            } else {
23487                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
23488            }
23489        }
23490
23491        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
23492            // TODO: mark this structure as dirty so we persist it!
23493            synchronized (mPackages) {
23494                final PackageSetting ps = mSettings.mPackages.get(packageName);
23495                if (ps != null) {
23496                    ps.setCeDataInode(ceDataInode, userId);
23497                }
23498            }
23499        }
23500
23501        prepareAppDataContentsLeafLIF(pkg, userId, flags);
23502    }
23503
23504    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
23505        if (pkg == null) {
23506            Slog.wtf(TAG, "Package was null!", new Throwable());
23507            return;
23508        }
23509        prepareAppDataContentsLeafLIF(pkg, userId, flags);
23510        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
23511        for (int i = 0; i < childCount; i++) {
23512            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
23513        }
23514    }
23515
23516    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
23517        final String volumeUuid = pkg.volumeUuid;
23518        final String packageName = pkg.packageName;
23519        final ApplicationInfo app = pkg.applicationInfo;
23520
23521        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
23522            // Create a native library symlink only if we have native libraries
23523            // and if the native libraries are 32 bit libraries. We do not provide
23524            // this symlink for 64 bit libraries.
23525            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
23526                final String nativeLibPath = app.nativeLibraryDir;
23527                try {
23528                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
23529                            nativeLibPath, userId);
23530                } catch (InstallerException e) {
23531                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
23532                }
23533            }
23534        }
23535    }
23536
23537    /**
23538     * For system apps on non-FBE devices, this method migrates any existing
23539     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
23540     * requested by the app.
23541     */
23542    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
23543        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
23544                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
23545            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
23546                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
23547            try {
23548                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
23549                        storageTarget);
23550            } catch (InstallerException e) {
23551                logCriticalInfo(Log.WARN,
23552                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
23553            }
23554            return true;
23555        } else {
23556            return false;
23557        }
23558    }
23559
23560    public PackageFreezer freezePackage(String packageName, String killReason) {
23561        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
23562    }
23563
23564    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
23565        return new PackageFreezer(packageName, userId, killReason);
23566    }
23567
23568    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
23569            String killReason) {
23570        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
23571    }
23572
23573    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
23574            String killReason) {
23575        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
23576            return new PackageFreezer();
23577        } else {
23578            return freezePackage(packageName, userId, killReason);
23579        }
23580    }
23581
23582    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
23583            String killReason) {
23584        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
23585    }
23586
23587    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
23588            String killReason) {
23589        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
23590            return new PackageFreezer();
23591        } else {
23592            return freezePackage(packageName, userId, killReason);
23593        }
23594    }
23595
23596    /**
23597     * Class that freezes and kills the given package upon creation, and
23598     * unfreezes it upon closing. This is typically used when doing surgery on
23599     * app code/data to prevent the app from running while you're working.
23600     */
23601    private class PackageFreezer implements AutoCloseable {
23602        private final String mPackageName;
23603        private final PackageFreezer[] mChildren;
23604
23605        private final boolean mWeFroze;
23606
23607        private final AtomicBoolean mClosed = new AtomicBoolean();
23608        private final CloseGuard mCloseGuard = CloseGuard.get();
23609
23610        /**
23611         * Create and return a stub freezer that doesn't actually do anything,
23612         * typically used when someone requested
23613         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
23614         * {@link PackageManager#DELETE_DONT_KILL_APP}.
23615         */
23616        public PackageFreezer() {
23617            mPackageName = null;
23618            mChildren = null;
23619            mWeFroze = false;
23620            mCloseGuard.open("close");
23621        }
23622
23623        public PackageFreezer(String packageName, int userId, String killReason) {
23624            synchronized (mPackages) {
23625                mPackageName = packageName;
23626                mWeFroze = mFrozenPackages.add(mPackageName);
23627
23628                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
23629                if (ps != null) {
23630                    killApplication(ps.name, ps.appId, userId, killReason);
23631                }
23632
23633                final PackageParser.Package p = mPackages.get(packageName);
23634                if (p != null && p.childPackages != null) {
23635                    final int N = p.childPackages.size();
23636                    mChildren = new PackageFreezer[N];
23637                    for (int i = 0; i < N; i++) {
23638                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
23639                                userId, killReason);
23640                    }
23641                } else {
23642                    mChildren = null;
23643                }
23644            }
23645            mCloseGuard.open("close");
23646        }
23647
23648        @Override
23649        protected void finalize() throws Throwable {
23650            try {
23651                if (mCloseGuard != null) {
23652                    mCloseGuard.warnIfOpen();
23653                }
23654
23655                close();
23656            } finally {
23657                super.finalize();
23658            }
23659        }
23660
23661        @Override
23662        public void close() {
23663            mCloseGuard.close();
23664            if (mClosed.compareAndSet(false, true)) {
23665                synchronized (mPackages) {
23666                    if (mWeFroze) {
23667                        mFrozenPackages.remove(mPackageName);
23668                    }
23669
23670                    if (mChildren != null) {
23671                        for (PackageFreezer freezer : mChildren) {
23672                            freezer.close();
23673                        }
23674                    }
23675                }
23676            }
23677        }
23678    }
23679
23680    /**
23681     * Verify that given package is currently frozen.
23682     */
23683    private void checkPackageFrozen(String packageName) {
23684        synchronized (mPackages) {
23685            if (!mFrozenPackages.contains(packageName)) {
23686                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
23687            }
23688        }
23689    }
23690
23691    @Override
23692    public int movePackage(final String packageName, final String volumeUuid) {
23693        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
23694
23695        final int callingUid = Binder.getCallingUid();
23696        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
23697        final int moveId = mNextMoveId.getAndIncrement();
23698        mHandler.post(new Runnable() {
23699            @Override
23700            public void run() {
23701                try {
23702                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
23703                } catch (PackageManagerException e) {
23704                    Slog.w(TAG, "Failed to move " + packageName, e);
23705                    mMoveCallbacks.notifyStatusChanged(moveId,
23706                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
23707                }
23708            }
23709        });
23710        return moveId;
23711    }
23712
23713    private void movePackageInternal(final String packageName, final String volumeUuid,
23714            final int moveId, final int callingUid, UserHandle user)
23715                    throws PackageManagerException {
23716        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23717        final PackageManager pm = mContext.getPackageManager();
23718
23719        final boolean currentAsec;
23720        final String currentVolumeUuid;
23721        final File codeFile;
23722        final String installerPackageName;
23723        final String packageAbiOverride;
23724        final int appId;
23725        final String seinfo;
23726        final String label;
23727        final int targetSdkVersion;
23728        final PackageFreezer freezer;
23729        final int[] installedUserIds;
23730
23731        // reader
23732        synchronized (mPackages) {
23733            final PackageParser.Package pkg = mPackages.get(packageName);
23734            final PackageSetting ps = mSettings.mPackages.get(packageName);
23735            if (pkg == null
23736                    || ps == null
23737                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
23738                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
23739            }
23740            if (pkg.applicationInfo.isSystemApp()) {
23741                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
23742                        "Cannot move system application");
23743            }
23744
23745            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
23746            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
23747                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
23748            if (isInternalStorage && !allow3rdPartyOnInternal) {
23749                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
23750                        "3rd party apps are not allowed on internal storage");
23751            }
23752
23753            if (pkg.applicationInfo.isExternalAsec()) {
23754                currentAsec = true;
23755                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
23756            } else if (pkg.applicationInfo.isForwardLocked()) {
23757                currentAsec = true;
23758                currentVolumeUuid = "forward_locked";
23759            } else {
23760                currentAsec = false;
23761                currentVolumeUuid = ps.volumeUuid;
23762
23763                final File probe = new File(pkg.codePath);
23764                final File probeOat = new File(probe, "oat");
23765                if (!probe.isDirectory() || !probeOat.isDirectory()) {
23766                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23767                            "Move only supported for modern cluster style installs");
23768                }
23769            }
23770
23771            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
23772                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23773                        "Package already moved to " + volumeUuid);
23774            }
23775            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
23776                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
23777                        "Device admin cannot be moved");
23778            }
23779
23780            if (mFrozenPackages.contains(packageName)) {
23781                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
23782                        "Failed to move already frozen package");
23783            }
23784
23785            codeFile = new File(pkg.codePath);
23786            installerPackageName = ps.installerPackageName;
23787            packageAbiOverride = ps.cpuAbiOverrideString;
23788            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
23789            seinfo = pkg.applicationInfo.seInfo;
23790            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
23791            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
23792            freezer = freezePackage(packageName, "movePackageInternal");
23793            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
23794        }
23795
23796        final Bundle extras = new Bundle();
23797        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
23798        extras.putString(Intent.EXTRA_TITLE, label);
23799        mMoveCallbacks.notifyCreated(moveId, extras);
23800
23801        int installFlags;
23802        final boolean moveCompleteApp;
23803        final File measurePath;
23804
23805        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
23806            installFlags = INSTALL_INTERNAL;
23807            moveCompleteApp = !currentAsec;
23808            measurePath = Environment.getDataAppDirectory(volumeUuid);
23809        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
23810            installFlags = INSTALL_EXTERNAL;
23811            moveCompleteApp = false;
23812            measurePath = storage.getPrimaryPhysicalVolume().getPath();
23813        } else {
23814            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
23815            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
23816                    || !volume.isMountedWritable()) {
23817                freezer.close();
23818                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23819                        "Move location not mounted private volume");
23820            }
23821
23822            Preconditions.checkState(!currentAsec);
23823
23824            installFlags = INSTALL_INTERNAL;
23825            moveCompleteApp = true;
23826            measurePath = Environment.getDataAppDirectory(volumeUuid);
23827        }
23828
23829        final PackageStats stats = new PackageStats(null, -1);
23830        synchronized (mInstaller) {
23831            for (int userId : installedUserIds) {
23832                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
23833                    freezer.close();
23834                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23835                            "Failed to measure package size");
23836                }
23837            }
23838        }
23839
23840        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
23841                + stats.dataSize);
23842
23843        final long startFreeBytes = measurePath.getUsableSpace();
23844        final long sizeBytes;
23845        if (moveCompleteApp) {
23846            sizeBytes = stats.codeSize + stats.dataSize;
23847        } else {
23848            sizeBytes = stats.codeSize;
23849        }
23850
23851        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
23852            freezer.close();
23853            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23854                    "Not enough free space to move");
23855        }
23856
23857        mMoveCallbacks.notifyStatusChanged(moveId, 10);
23858
23859        final CountDownLatch installedLatch = new CountDownLatch(1);
23860        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
23861            @Override
23862            public void onUserActionRequired(Intent intent) throws RemoteException {
23863                throw new IllegalStateException();
23864            }
23865
23866            @Override
23867            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
23868                    Bundle extras) throws RemoteException {
23869                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
23870                        + PackageManager.installStatusToString(returnCode, msg));
23871
23872                installedLatch.countDown();
23873                freezer.close();
23874
23875                final int status = PackageManager.installStatusToPublicStatus(returnCode);
23876                switch (status) {
23877                    case PackageInstaller.STATUS_SUCCESS:
23878                        mMoveCallbacks.notifyStatusChanged(moveId,
23879                                PackageManager.MOVE_SUCCEEDED);
23880                        break;
23881                    case PackageInstaller.STATUS_FAILURE_STORAGE:
23882                        mMoveCallbacks.notifyStatusChanged(moveId,
23883                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
23884                        break;
23885                    default:
23886                        mMoveCallbacks.notifyStatusChanged(moveId,
23887                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
23888                        break;
23889                }
23890            }
23891        };
23892
23893        final MoveInfo move;
23894        if (moveCompleteApp) {
23895            // Kick off a thread to report progress estimates
23896            new Thread() {
23897                @Override
23898                public void run() {
23899                    while (true) {
23900                        try {
23901                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
23902                                break;
23903                            }
23904                        } catch (InterruptedException ignored) {
23905                        }
23906
23907                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
23908                        final int progress = 10 + (int) MathUtils.constrain(
23909                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
23910                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
23911                    }
23912                }
23913            }.start();
23914
23915            final String dataAppName = codeFile.getName();
23916            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
23917                    dataAppName, appId, seinfo, targetSdkVersion);
23918        } else {
23919            move = null;
23920        }
23921
23922        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
23923
23924        final Message msg = mHandler.obtainMessage(INIT_COPY);
23925        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
23926        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
23927                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
23928                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
23929                PackageManager.INSTALL_REASON_UNKNOWN);
23930        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
23931        msg.obj = params;
23932
23933        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
23934                System.identityHashCode(msg.obj));
23935        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
23936                System.identityHashCode(msg.obj));
23937
23938        mHandler.sendMessage(msg);
23939    }
23940
23941    @Override
23942    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
23943        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
23944
23945        final int realMoveId = mNextMoveId.getAndIncrement();
23946        final Bundle extras = new Bundle();
23947        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
23948        mMoveCallbacks.notifyCreated(realMoveId, extras);
23949
23950        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
23951            @Override
23952            public void onCreated(int moveId, Bundle extras) {
23953                // Ignored
23954            }
23955
23956            @Override
23957            public void onStatusChanged(int moveId, int status, long estMillis) {
23958                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
23959            }
23960        };
23961
23962        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23963        storage.setPrimaryStorageUuid(volumeUuid, callback);
23964        return realMoveId;
23965    }
23966
23967    @Override
23968    public int getMoveStatus(int moveId) {
23969        mContext.enforceCallingOrSelfPermission(
23970                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23971        return mMoveCallbacks.mLastStatus.get(moveId);
23972    }
23973
23974    @Override
23975    public void registerMoveCallback(IPackageMoveObserver callback) {
23976        mContext.enforceCallingOrSelfPermission(
23977                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23978        mMoveCallbacks.register(callback);
23979    }
23980
23981    @Override
23982    public void unregisterMoveCallback(IPackageMoveObserver callback) {
23983        mContext.enforceCallingOrSelfPermission(
23984                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23985        mMoveCallbacks.unregister(callback);
23986    }
23987
23988    @Override
23989    public boolean setInstallLocation(int loc) {
23990        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
23991                null);
23992        if (getInstallLocation() == loc) {
23993            return true;
23994        }
23995        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
23996                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
23997            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
23998                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
23999            return true;
24000        }
24001        return false;
24002   }
24003
24004    @Override
24005    public int getInstallLocation() {
24006        // allow instant app access
24007        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
24008                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
24009                PackageHelper.APP_INSTALL_AUTO);
24010    }
24011
24012    /** Called by UserManagerService */
24013    void cleanUpUser(UserManagerService userManager, int userHandle) {
24014        synchronized (mPackages) {
24015            mDirtyUsers.remove(userHandle);
24016            mUserNeedsBadging.delete(userHandle);
24017            mSettings.removeUserLPw(userHandle);
24018            mPendingBroadcasts.remove(userHandle);
24019            mInstantAppRegistry.onUserRemovedLPw(userHandle);
24020            removeUnusedPackagesLPw(userManager, userHandle);
24021        }
24022    }
24023
24024    /**
24025     * We're removing userHandle and would like to remove any downloaded packages
24026     * that are no longer in use by any other user.
24027     * @param userHandle the user being removed
24028     */
24029    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
24030        final boolean DEBUG_CLEAN_APKS = false;
24031        int [] users = userManager.getUserIds();
24032        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
24033        while (psit.hasNext()) {
24034            PackageSetting ps = psit.next();
24035            if (ps.pkg == null) {
24036                continue;
24037            }
24038            final String packageName = ps.pkg.packageName;
24039            // Skip over if system app
24040            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
24041                continue;
24042            }
24043            if (DEBUG_CLEAN_APKS) {
24044                Slog.i(TAG, "Checking package " + packageName);
24045            }
24046            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
24047            if (keep) {
24048                if (DEBUG_CLEAN_APKS) {
24049                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
24050                }
24051            } else {
24052                for (int i = 0; i < users.length; i++) {
24053                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
24054                        keep = true;
24055                        if (DEBUG_CLEAN_APKS) {
24056                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
24057                                    + users[i]);
24058                        }
24059                        break;
24060                    }
24061                }
24062            }
24063            if (!keep) {
24064                if (DEBUG_CLEAN_APKS) {
24065                    Slog.i(TAG, "  Removing package " + packageName);
24066                }
24067                mHandler.post(new Runnable() {
24068                    public void run() {
24069                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
24070                                userHandle, 0);
24071                    } //end run
24072                });
24073            }
24074        }
24075    }
24076
24077    /** Called by UserManagerService */
24078    void createNewUser(int userId, String[] disallowedPackages) {
24079        synchronized (mInstallLock) {
24080            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
24081        }
24082        synchronized (mPackages) {
24083            scheduleWritePackageRestrictionsLocked(userId);
24084            scheduleWritePackageListLocked(userId);
24085            applyFactoryDefaultBrowserLPw(userId);
24086            primeDomainVerificationsLPw(userId);
24087        }
24088    }
24089
24090    void onNewUserCreated(final int userId) {
24091        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
24092        // If permission review for legacy apps is required, we represent
24093        // dagerous permissions for such apps as always granted runtime
24094        // permissions to keep per user flag state whether review is needed.
24095        // Hence, if a new user is added we have to propagate dangerous
24096        // permission grants for these legacy apps.
24097        if (mPermissionReviewRequired) {
24098            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
24099                    | UPDATE_PERMISSIONS_REPLACE_ALL);
24100        }
24101    }
24102
24103    @Override
24104    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
24105        mContext.enforceCallingOrSelfPermission(
24106                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
24107                "Only package verification agents can read the verifier device identity");
24108
24109        synchronized (mPackages) {
24110            return mSettings.getVerifierDeviceIdentityLPw();
24111        }
24112    }
24113
24114    @Override
24115    public void setPermissionEnforced(String permission, boolean enforced) {
24116        // TODO: Now that we no longer change GID for storage, this should to away.
24117        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
24118                "setPermissionEnforced");
24119        if (READ_EXTERNAL_STORAGE.equals(permission)) {
24120            synchronized (mPackages) {
24121                if (mSettings.mReadExternalStorageEnforced == null
24122                        || mSettings.mReadExternalStorageEnforced != enforced) {
24123                    mSettings.mReadExternalStorageEnforced = enforced;
24124                    mSettings.writeLPr();
24125                }
24126            }
24127            // kill any non-foreground processes so we restart them and
24128            // grant/revoke the GID.
24129            final IActivityManager am = ActivityManager.getService();
24130            if (am != null) {
24131                final long token = Binder.clearCallingIdentity();
24132                try {
24133                    am.killProcessesBelowForeground("setPermissionEnforcement");
24134                } catch (RemoteException e) {
24135                } finally {
24136                    Binder.restoreCallingIdentity(token);
24137                }
24138            }
24139        } else {
24140            throw new IllegalArgumentException("No selective enforcement for " + permission);
24141        }
24142    }
24143
24144    @Override
24145    @Deprecated
24146    public boolean isPermissionEnforced(String permission) {
24147        // allow instant applications
24148        return true;
24149    }
24150
24151    @Override
24152    public boolean isStorageLow() {
24153        // allow instant applications
24154        final long token = Binder.clearCallingIdentity();
24155        try {
24156            final DeviceStorageMonitorInternal
24157                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
24158            if (dsm != null) {
24159                return dsm.isMemoryLow();
24160            } else {
24161                return false;
24162            }
24163        } finally {
24164            Binder.restoreCallingIdentity(token);
24165        }
24166    }
24167
24168    @Override
24169    public IPackageInstaller getPackageInstaller() {
24170        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24171            return null;
24172        }
24173        return mInstallerService;
24174    }
24175
24176    private boolean userNeedsBadging(int userId) {
24177        int index = mUserNeedsBadging.indexOfKey(userId);
24178        if (index < 0) {
24179            final UserInfo userInfo;
24180            final long token = Binder.clearCallingIdentity();
24181            try {
24182                userInfo = sUserManager.getUserInfo(userId);
24183            } finally {
24184                Binder.restoreCallingIdentity(token);
24185            }
24186            final boolean b;
24187            if (userInfo != null && userInfo.isManagedProfile()) {
24188                b = true;
24189            } else {
24190                b = false;
24191            }
24192            mUserNeedsBadging.put(userId, b);
24193            return b;
24194        }
24195        return mUserNeedsBadging.valueAt(index);
24196    }
24197
24198    @Override
24199    public KeySet getKeySetByAlias(String packageName, String alias) {
24200        if (packageName == null || alias == null) {
24201            return null;
24202        }
24203        synchronized(mPackages) {
24204            final PackageParser.Package pkg = mPackages.get(packageName);
24205            if (pkg == null) {
24206                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24207                throw new IllegalArgumentException("Unknown package: " + packageName);
24208            }
24209            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24210            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
24211                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
24212                throw new IllegalArgumentException("Unknown package: " + packageName);
24213            }
24214            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24215            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
24216        }
24217    }
24218
24219    @Override
24220    public KeySet getSigningKeySet(String packageName) {
24221        if (packageName == null) {
24222            return null;
24223        }
24224        synchronized(mPackages) {
24225            final int callingUid = Binder.getCallingUid();
24226            final int callingUserId = UserHandle.getUserId(callingUid);
24227            final PackageParser.Package pkg = mPackages.get(packageName);
24228            if (pkg == null) {
24229                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24230                throw new IllegalArgumentException("Unknown package: " + packageName);
24231            }
24232            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24233            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
24234                // filter and pretend the package doesn't exist
24235                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
24236                        + ", uid:" + callingUid);
24237                throw new IllegalArgumentException("Unknown package: " + packageName);
24238            }
24239            if (pkg.applicationInfo.uid != callingUid
24240                    && Process.SYSTEM_UID != callingUid) {
24241                throw new SecurityException("May not access signing KeySet of other apps.");
24242            }
24243            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24244            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
24245        }
24246    }
24247
24248    @Override
24249    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
24250        final int callingUid = Binder.getCallingUid();
24251        if (getInstantAppPackageName(callingUid) != null) {
24252            return false;
24253        }
24254        if (packageName == null || ks == null) {
24255            return false;
24256        }
24257        synchronized(mPackages) {
24258            final PackageParser.Package pkg = mPackages.get(packageName);
24259            if (pkg == null
24260                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24261                            UserHandle.getUserId(callingUid))) {
24262                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24263                throw new IllegalArgumentException("Unknown package: " + packageName);
24264            }
24265            IBinder ksh = ks.getToken();
24266            if (ksh instanceof KeySetHandle) {
24267                KeySetManagerService ksms = mSettings.mKeySetManagerService;
24268                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
24269            }
24270            return false;
24271        }
24272    }
24273
24274    @Override
24275    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
24276        final int callingUid = Binder.getCallingUid();
24277        if (getInstantAppPackageName(callingUid) != null) {
24278            return false;
24279        }
24280        if (packageName == null || ks == null) {
24281            return false;
24282        }
24283        synchronized(mPackages) {
24284            final PackageParser.Package pkg = mPackages.get(packageName);
24285            if (pkg == null
24286                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24287                            UserHandle.getUserId(callingUid))) {
24288                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24289                throw new IllegalArgumentException("Unknown package: " + packageName);
24290            }
24291            IBinder ksh = ks.getToken();
24292            if (ksh instanceof KeySetHandle) {
24293                KeySetManagerService ksms = mSettings.mKeySetManagerService;
24294                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
24295            }
24296            return false;
24297        }
24298    }
24299
24300    private void deletePackageIfUnusedLPr(final String packageName) {
24301        PackageSetting ps = mSettings.mPackages.get(packageName);
24302        if (ps == null) {
24303            return;
24304        }
24305        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
24306            // TODO Implement atomic delete if package is unused
24307            // It is currently possible that the package will be deleted even if it is installed
24308            // after this method returns.
24309            mHandler.post(new Runnable() {
24310                public void run() {
24311                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
24312                            0, PackageManager.DELETE_ALL_USERS);
24313                }
24314            });
24315        }
24316    }
24317
24318    /**
24319     * Check and throw if the given before/after packages would be considered a
24320     * downgrade.
24321     */
24322    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
24323            throws PackageManagerException {
24324        if (after.versionCode < before.mVersionCode) {
24325            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24326                    "Update version code " + after.versionCode + " is older than current "
24327                    + before.mVersionCode);
24328        } else if (after.versionCode == before.mVersionCode) {
24329            if (after.baseRevisionCode < before.baseRevisionCode) {
24330                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24331                        "Update base revision code " + after.baseRevisionCode
24332                        + " is older than current " + before.baseRevisionCode);
24333            }
24334
24335            if (!ArrayUtils.isEmpty(after.splitNames)) {
24336                for (int i = 0; i < after.splitNames.length; i++) {
24337                    final String splitName = after.splitNames[i];
24338                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
24339                    if (j != -1) {
24340                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
24341                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24342                                    "Update split " + splitName + " revision code "
24343                                    + after.splitRevisionCodes[i] + " is older than current "
24344                                    + before.splitRevisionCodes[j]);
24345                        }
24346                    }
24347                }
24348            }
24349        }
24350    }
24351
24352    private static class MoveCallbacks extends Handler {
24353        private static final int MSG_CREATED = 1;
24354        private static final int MSG_STATUS_CHANGED = 2;
24355
24356        private final RemoteCallbackList<IPackageMoveObserver>
24357                mCallbacks = new RemoteCallbackList<>();
24358
24359        private final SparseIntArray mLastStatus = new SparseIntArray();
24360
24361        public MoveCallbacks(Looper looper) {
24362            super(looper);
24363        }
24364
24365        public void register(IPackageMoveObserver callback) {
24366            mCallbacks.register(callback);
24367        }
24368
24369        public void unregister(IPackageMoveObserver callback) {
24370            mCallbacks.unregister(callback);
24371        }
24372
24373        @Override
24374        public void handleMessage(Message msg) {
24375            final SomeArgs args = (SomeArgs) msg.obj;
24376            final int n = mCallbacks.beginBroadcast();
24377            for (int i = 0; i < n; i++) {
24378                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
24379                try {
24380                    invokeCallback(callback, msg.what, args);
24381                } catch (RemoteException ignored) {
24382                }
24383            }
24384            mCallbacks.finishBroadcast();
24385            args.recycle();
24386        }
24387
24388        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
24389                throws RemoteException {
24390            switch (what) {
24391                case MSG_CREATED: {
24392                    callback.onCreated(args.argi1, (Bundle) args.arg2);
24393                    break;
24394                }
24395                case MSG_STATUS_CHANGED: {
24396                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
24397                    break;
24398                }
24399            }
24400        }
24401
24402        private void notifyCreated(int moveId, Bundle extras) {
24403            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
24404
24405            final SomeArgs args = SomeArgs.obtain();
24406            args.argi1 = moveId;
24407            args.arg2 = extras;
24408            obtainMessage(MSG_CREATED, args).sendToTarget();
24409        }
24410
24411        private void notifyStatusChanged(int moveId, int status) {
24412            notifyStatusChanged(moveId, status, -1);
24413        }
24414
24415        private void notifyStatusChanged(int moveId, int status, long estMillis) {
24416            Slog.v(TAG, "Move " + moveId + " status " + status);
24417
24418            final SomeArgs args = SomeArgs.obtain();
24419            args.argi1 = moveId;
24420            args.argi2 = status;
24421            args.arg3 = estMillis;
24422            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
24423
24424            synchronized (mLastStatus) {
24425                mLastStatus.put(moveId, status);
24426            }
24427        }
24428    }
24429
24430    private final static class OnPermissionChangeListeners extends Handler {
24431        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
24432
24433        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
24434                new RemoteCallbackList<>();
24435
24436        public OnPermissionChangeListeners(Looper looper) {
24437            super(looper);
24438        }
24439
24440        @Override
24441        public void handleMessage(Message msg) {
24442            switch (msg.what) {
24443                case MSG_ON_PERMISSIONS_CHANGED: {
24444                    final int uid = msg.arg1;
24445                    handleOnPermissionsChanged(uid);
24446                } break;
24447            }
24448        }
24449
24450        public void addListenerLocked(IOnPermissionsChangeListener listener) {
24451            mPermissionListeners.register(listener);
24452
24453        }
24454
24455        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
24456            mPermissionListeners.unregister(listener);
24457        }
24458
24459        public void onPermissionsChanged(int uid) {
24460            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
24461                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
24462            }
24463        }
24464
24465        private void handleOnPermissionsChanged(int uid) {
24466            final int count = mPermissionListeners.beginBroadcast();
24467            try {
24468                for (int i = 0; i < count; i++) {
24469                    IOnPermissionsChangeListener callback = mPermissionListeners
24470                            .getBroadcastItem(i);
24471                    try {
24472                        callback.onPermissionsChanged(uid);
24473                    } catch (RemoteException e) {
24474                        Log.e(TAG, "Permission listener is dead", e);
24475                    }
24476                }
24477            } finally {
24478                mPermissionListeners.finishBroadcast();
24479            }
24480        }
24481    }
24482
24483    private class PackageManagerInternalImpl extends PackageManagerInternal {
24484        @Override
24485        public void setLocationPackagesProvider(PackagesProvider provider) {
24486            synchronized (mPackages) {
24487                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
24488            }
24489        }
24490
24491        @Override
24492        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
24493            synchronized (mPackages) {
24494                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
24495            }
24496        }
24497
24498        @Override
24499        public void setSmsAppPackagesProvider(PackagesProvider provider) {
24500            synchronized (mPackages) {
24501                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
24502            }
24503        }
24504
24505        @Override
24506        public void setDialerAppPackagesProvider(PackagesProvider provider) {
24507            synchronized (mPackages) {
24508                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
24509            }
24510        }
24511
24512        @Override
24513        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
24514            synchronized (mPackages) {
24515                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
24516            }
24517        }
24518
24519        @Override
24520        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
24521            synchronized (mPackages) {
24522                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
24523            }
24524        }
24525
24526        @Override
24527        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
24528            synchronized (mPackages) {
24529                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
24530                        packageName, userId);
24531            }
24532        }
24533
24534        @Override
24535        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
24536            synchronized (mPackages) {
24537                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
24538                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
24539                        packageName, userId);
24540            }
24541        }
24542
24543        @Override
24544        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
24545            synchronized (mPackages) {
24546                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
24547                        packageName, userId);
24548            }
24549        }
24550
24551        @Override
24552        public void setKeepUninstalledPackages(final List<String> packageList) {
24553            Preconditions.checkNotNull(packageList);
24554            List<String> removedFromList = null;
24555            synchronized (mPackages) {
24556                if (mKeepUninstalledPackages != null) {
24557                    final int packagesCount = mKeepUninstalledPackages.size();
24558                    for (int i = 0; i < packagesCount; i++) {
24559                        String oldPackage = mKeepUninstalledPackages.get(i);
24560                        if (packageList != null && packageList.contains(oldPackage)) {
24561                            continue;
24562                        }
24563                        if (removedFromList == null) {
24564                            removedFromList = new ArrayList<>();
24565                        }
24566                        removedFromList.add(oldPackage);
24567                    }
24568                }
24569                mKeepUninstalledPackages = new ArrayList<>(packageList);
24570                if (removedFromList != null) {
24571                    final int removedCount = removedFromList.size();
24572                    for (int i = 0; i < removedCount; i++) {
24573                        deletePackageIfUnusedLPr(removedFromList.get(i));
24574                    }
24575                }
24576            }
24577        }
24578
24579        @Override
24580        public boolean isPermissionsReviewRequired(String packageName, int userId) {
24581            synchronized (mPackages) {
24582                // If we do not support permission review, done.
24583                if (!mPermissionReviewRequired) {
24584                    return false;
24585                }
24586
24587                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
24588                if (packageSetting == null) {
24589                    return false;
24590                }
24591
24592                // Permission review applies only to apps not supporting the new permission model.
24593                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
24594                    return false;
24595                }
24596
24597                // Legacy apps have the permission and get user consent on launch.
24598                PermissionsState permissionsState = packageSetting.getPermissionsState();
24599                return permissionsState.isPermissionReviewRequired(userId);
24600            }
24601        }
24602
24603        @Override
24604        public PackageInfo getPackageInfo(
24605                String packageName, int flags, int filterCallingUid, int userId) {
24606            return PackageManagerService.this
24607                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
24608                            flags, filterCallingUid, userId);
24609        }
24610
24611        @Override
24612        public ApplicationInfo getApplicationInfo(
24613                String packageName, int flags, int filterCallingUid, int userId) {
24614            return PackageManagerService.this
24615                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
24616        }
24617
24618        @Override
24619        public ActivityInfo getActivityInfo(
24620                ComponentName component, int flags, int filterCallingUid, int userId) {
24621            return PackageManagerService.this
24622                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
24623        }
24624
24625        @Override
24626        public List<ResolveInfo> queryIntentActivities(
24627                Intent intent, int flags, int filterCallingUid, int userId) {
24628            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
24629            return PackageManagerService.this
24630                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
24631                            userId, false /*resolveForStart*/);
24632        }
24633
24634        @Override
24635        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
24636                int userId) {
24637            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
24638        }
24639
24640        @Override
24641        public void setDeviceAndProfileOwnerPackages(
24642                int deviceOwnerUserId, String deviceOwnerPackage,
24643                SparseArray<String> profileOwnerPackages) {
24644            mProtectedPackages.setDeviceAndProfileOwnerPackages(
24645                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
24646        }
24647
24648        @Override
24649        public boolean isPackageDataProtected(int userId, String packageName) {
24650            return mProtectedPackages.isPackageDataProtected(userId, packageName);
24651        }
24652
24653        @Override
24654        public boolean isPackageEphemeral(int userId, String packageName) {
24655            synchronized (mPackages) {
24656                final PackageSetting ps = mSettings.mPackages.get(packageName);
24657                return ps != null ? ps.getInstantApp(userId) : false;
24658            }
24659        }
24660
24661        @Override
24662        public boolean wasPackageEverLaunched(String packageName, int userId) {
24663            synchronized (mPackages) {
24664                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
24665            }
24666        }
24667
24668        @Override
24669        public void grantRuntimePermission(String packageName, String name, int userId,
24670                boolean overridePolicy) {
24671            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
24672                    overridePolicy);
24673        }
24674
24675        @Override
24676        public void revokeRuntimePermission(String packageName, String name, int userId,
24677                boolean overridePolicy) {
24678            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
24679                    overridePolicy);
24680        }
24681
24682        @Override
24683        public String getNameForUid(int uid) {
24684            return PackageManagerService.this.getNameForUid(uid);
24685        }
24686
24687        @Override
24688        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
24689                Intent origIntent, String resolvedType, String callingPackage,
24690                Bundle verificationBundle, int userId) {
24691            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
24692                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
24693                    userId);
24694        }
24695
24696        @Override
24697        public void grantEphemeralAccess(int userId, Intent intent,
24698                int targetAppId, int ephemeralAppId) {
24699            synchronized (mPackages) {
24700                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
24701                        targetAppId, ephemeralAppId);
24702            }
24703        }
24704
24705        @Override
24706        public boolean isInstantAppInstallerComponent(ComponentName component) {
24707            synchronized (mPackages) {
24708                return mInstantAppInstallerActivity != null
24709                        && mInstantAppInstallerActivity.getComponentName().equals(component);
24710            }
24711        }
24712
24713        @Override
24714        public void pruneInstantApps() {
24715            mInstantAppRegistry.pruneInstantApps();
24716        }
24717
24718        @Override
24719        public String getSetupWizardPackageName() {
24720            return mSetupWizardPackage;
24721        }
24722
24723        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
24724            if (policy != null) {
24725                mExternalSourcesPolicy = policy;
24726            }
24727        }
24728
24729        @Override
24730        public boolean isPackagePersistent(String packageName) {
24731            synchronized (mPackages) {
24732                PackageParser.Package pkg = mPackages.get(packageName);
24733                return pkg != null
24734                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
24735                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
24736                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
24737                        : false;
24738            }
24739        }
24740
24741        @Override
24742        public List<PackageInfo> getOverlayPackages(int userId) {
24743            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
24744            synchronized (mPackages) {
24745                for (PackageParser.Package p : mPackages.values()) {
24746                    if (p.mOverlayTarget != null) {
24747                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
24748                        if (pkg != null) {
24749                            overlayPackages.add(pkg);
24750                        }
24751                    }
24752                }
24753            }
24754            return overlayPackages;
24755        }
24756
24757        @Override
24758        public List<String> getTargetPackageNames(int userId) {
24759            List<String> targetPackages = new ArrayList<>();
24760            synchronized (mPackages) {
24761                for (PackageParser.Package p : mPackages.values()) {
24762                    if (p.mOverlayTarget == null) {
24763                        targetPackages.add(p.packageName);
24764                    }
24765                }
24766            }
24767            return targetPackages;
24768        }
24769
24770        @Override
24771        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
24772                @Nullable List<String> overlayPackageNames) {
24773            synchronized (mPackages) {
24774                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
24775                    Slog.e(TAG, "failed to find package " + targetPackageName);
24776                    return false;
24777                }
24778                ArrayList<String> overlayPaths = null;
24779                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
24780                    final int N = overlayPackageNames.size();
24781                    overlayPaths = new ArrayList<>(N);
24782                    for (int i = 0; i < N; i++) {
24783                        final String packageName = overlayPackageNames.get(i);
24784                        final PackageParser.Package pkg = mPackages.get(packageName);
24785                        if (pkg == null) {
24786                            Slog.e(TAG, "failed to find package " + packageName);
24787                            return false;
24788                        }
24789                        overlayPaths.add(pkg.baseCodePath);
24790                    }
24791                }
24792
24793                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
24794                ps.setOverlayPaths(overlayPaths, userId);
24795                return true;
24796            }
24797        }
24798
24799        @Override
24800        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
24801                int flags, int userId) {
24802            return resolveIntentInternal(
24803                    intent, resolvedType, flags, userId, true /*resolveForStart*/);
24804        }
24805
24806        @Override
24807        public ResolveInfo resolveService(Intent intent, String resolvedType,
24808                int flags, int userId, int callingUid) {
24809            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
24810        }
24811
24812        @Override
24813        public void addIsolatedUid(int isolatedUid, int ownerUid) {
24814            synchronized (mPackages) {
24815                mIsolatedOwners.put(isolatedUid, ownerUid);
24816            }
24817        }
24818
24819        @Override
24820        public void removeIsolatedUid(int isolatedUid) {
24821            synchronized (mPackages) {
24822                mIsolatedOwners.delete(isolatedUid);
24823            }
24824        }
24825
24826        @Override
24827        public int getUidTargetSdkVersion(int uid) {
24828            synchronized (mPackages) {
24829                return getUidTargetSdkVersionLockedLPr(uid);
24830            }
24831        }
24832
24833        @Override
24834        public boolean canAccessInstantApps(int callingUid, int userId) {
24835            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
24836        }
24837    }
24838
24839    @Override
24840    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
24841        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
24842        synchronized (mPackages) {
24843            final long identity = Binder.clearCallingIdentity();
24844            try {
24845                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
24846                        packageNames, userId);
24847            } finally {
24848                Binder.restoreCallingIdentity(identity);
24849            }
24850        }
24851    }
24852
24853    @Override
24854    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
24855        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
24856        synchronized (mPackages) {
24857            final long identity = Binder.clearCallingIdentity();
24858            try {
24859                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr(
24860                        packageNames, userId);
24861            } finally {
24862                Binder.restoreCallingIdentity(identity);
24863            }
24864        }
24865    }
24866
24867    private static void enforceSystemOrPhoneCaller(String tag) {
24868        int callingUid = Binder.getCallingUid();
24869        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
24870            throw new SecurityException(
24871                    "Cannot call " + tag + " from UID " + callingUid);
24872        }
24873    }
24874
24875    boolean isHistoricalPackageUsageAvailable() {
24876        return mPackageUsage.isHistoricalPackageUsageAvailable();
24877    }
24878
24879    /**
24880     * Return a <b>copy</b> of the collection of packages known to the package manager.
24881     * @return A copy of the values of mPackages.
24882     */
24883    Collection<PackageParser.Package> getPackages() {
24884        synchronized (mPackages) {
24885            return new ArrayList<>(mPackages.values());
24886        }
24887    }
24888
24889    /**
24890     * Logs process start information (including base APK hash) to the security log.
24891     * @hide
24892     */
24893    @Override
24894    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
24895            String apkFile, int pid) {
24896        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24897            return;
24898        }
24899        if (!SecurityLog.isLoggingEnabled()) {
24900            return;
24901        }
24902        Bundle data = new Bundle();
24903        data.putLong("startTimestamp", System.currentTimeMillis());
24904        data.putString("processName", processName);
24905        data.putInt("uid", uid);
24906        data.putString("seinfo", seinfo);
24907        data.putString("apkFile", apkFile);
24908        data.putInt("pid", pid);
24909        Message msg = mProcessLoggingHandler.obtainMessage(
24910                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
24911        msg.setData(data);
24912        mProcessLoggingHandler.sendMessage(msg);
24913    }
24914
24915    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
24916        return mCompilerStats.getPackageStats(pkgName);
24917    }
24918
24919    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
24920        return getOrCreateCompilerPackageStats(pkg.packageName);
24921    }
24922
24923    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
24924        return mCompilerStats.getOrCreatePackageStats(pkgName);
24925    }
24926
24927    public void deleteCompilerPackageStats(String pkgName) {
24928        mCompilerStats.deletePackageStats(pkgName);
24929    }
24930
24931    @Override
24932    public int getInstallReason(String packageName, int userId) {
24933        final int callingUid = Binder.getCallingUid();
24934        enforceCrossUserPermission(callingUid, userId,
24935                true /* requireFullPermission */, false /* checkShell */,
24936                "get install reason");
24937        synchronized (mPackages) {
24938            final PackageSetting ps = mSettings.mPackages.get(packageName);
24939            if (filterAppAccessLPr(ps, callingUid, userId)) {
24940                return PackageManager.INSTALL_REASON_UNKNOWN;
24941            }
24942            if (ps != null) {
24943                return ps.getInstallReason(userId);
24944            }
24945        }
24946        return PackageManager.INSTALL_REASON_UNKNOWN;
24947    }
24948
24949    @Override
24950    public boolean canRequestPackageInstalls(String packageName, int userId) {
24951        return canRequestPackageInstallsInternal(packageName, 0, userId,
24952                true /* throwIfPermNotDeclared*/);
24953    }
24954
24955    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
24956            boolean throwIfPermNotDeclared) {
24957        int callingUid = Binder.getCallingUid();
24958        int uid = getPackageUid(packageName, 0, userId);
24959        if (callingUid != uid && callingUid != Process.ROOT_UID
24960                && callingUid != Process.SYSTEM_UID) {
24961            throw new SecurityException(
24962                    "Caller uid " + callingUid + " does not own package " + packageName);
24963        }
24964        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
24965        if (info == null) {
24966            return false;
24967        }
24968        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
24969            return false;
24970        }
24971        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
24972        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
24973        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
24974            if (throwIfPermNotDeclared) {
24975                throw new SecurityException("Need to declare " + appOpPermission
24976                        + " to call this api");
24977            } else {
24978                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
24979                return false;
24980            }
24981        }
24982        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
24983            return false;
24984        }
24985        if (mExternalSourcesPolicy != null) {
24986            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
24987            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
24988                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
24989            }
24990        }
24991        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
24992    }
24993
24994    @Override
24995    public ComponentName getInstantAppResolverSettingsComponent() {
24996        return mInstantAppResolverSettingsComponent;
24997    }
24998
24999    @Override
25000    public ComponentName getInstantAppInstallerComponent() {
25001        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
25002            return null;
25003        }
25004        return mInstantAppInstallerActivity == null
25005                ? null : mInstantAppInstallerActivity.getComponentName();
25006    }
25007
25008    @Override
25009    public String getInstantAppAndroidId(String packageName, int userId) {
25010        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
25011                "getInstantAppAndroidId");
25012        enforceCrossUserPermission(Binder.getCallingUid(), userId,
25013                true /* requireFullPermission */, false /* checkShell */,
25014                "getInstantAppAndroidId");
25015        // Make sure the target is an Instant App.
25016        if (!isInstantApp(packageName, userId)) {
25017            return null;
25018        }
25019        synchronized (mPackages) {
25020            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
25021        }
25022    }
25023
25024    boolean canHaveOatDir(String packageName) {
25025        synchronized (mPackages) {
25026            PackageParser.Package p = mPackages.get(packageName);
25027            if (p == null) {
25028                return false;
25029            }
25030            return p.canHaveOatDir();
25031        }
25032    }
25033
25034    private String getOatDir(PackageParser.Package pkg) {
25035        if (!pkg.canHaveOatDir()) {
25036            return null;
25037        }
25038        File codePath = new File(pkg.codePath);
25039        if (codePath.isDirectory()) {
25040            return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath();
25041        }
25042        return null;
25043    }
25044
25045    void deleteOatArtifactsOfPackage(String packageName) {
25046        final String[] instructionSets;
25047        final List<String> codePaths;
25048        final String oatDir;
25049        final PackageParser.Package pkg;
25050        synchronized (mPackages) {
25051            pkg = mPackages.get(packageName);
25052        }
25053        instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
25054        codePaths = pkg.getAllCodePaths();
25055        oatDir = getOatDir(pkg);
25056
25057        for (String codePath : codePaths) {
25058            for (String isa : instructionSets) {
25059                try {
25060                    mInstaller.deleteOdex(codePath, isa, oatDir);
25061                } catch (InstallerException e) {
25062                    Log.e(TAG, "Failed deleting oat files for " + codePath, e);
25063                }
25064            }
25065        }
25066    }
25067
25068    Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) {
25069        Set<String> unusedPackages = new HashSet<>();
25070        long currentTimeInMillis = System.currentTimeMillis();
25071        synchronized (mPackages) {
25072            for (PackageParser.Package pkg : mPackages.values()) {
25073                PackageSetting ps =  mSettings.mPackages.get(pkg.packageName);
25074                if (ps == null) {
25075                    continue;
25076                }
25077                PackageDexUsage.PackageUseInfo packageUseInfo = getDexManager().getPackageUseInfo(
25078                        pkg.packageName);
25079                if (PackageManagerServiceUtils
25080                        .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis,
25081                                downgradeTimeThresholdMillis, packageUseInfo,
25082                                pkg.getLatestPackageUseTimeInMills(),
25083                                pkg.getLatestForegroundPackageUseTimeInMills())) {
25084                    unusedPackages.add(pkg.packageName);
25085                }
25086            }
25087        }
25088        return unusedPackages;
25089    }
25090}
25091
25092interface PackageSender {
25093    void sendPackageBroadcast(final String action, final String pkg,
25094        final Bundle extras, final int flags, final String targetPkg,
25095        final IIntentReceiver finishedReceiver, final int[] userIds);
25096    void sendPackageAddedForNewUsers(String packageName, boolean isSystem,
25097        int appId, int... userIds);
25098}
25099