PackageManagerService.java revision b274947dfb03f04872546774af0f8770ade5bed7
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.READ_EXTERNAL_STORAGE;
22import static android.Manifest.permission.REQUEST_DELETE_PACKAGES;
23import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
24import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
27import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
28import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
29import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
30import static android.content.pm.PackageManager.DELETE_KEEP_DATA;
31import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
33import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
34import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
35import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
36import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
37import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
38import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
39import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
40import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
41import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
42import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
43import static android.content.pm.PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID;
44import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
45import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
46import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
47import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
48import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
49import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
50import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
51import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
52import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
53import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
54import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
55import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
56import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
57import static android.content.pm.PackageManager.INSTALL_INTERNAL;
58import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
62import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
63import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
64import static android.content.pm.PackageManager.MATCH_ALL;
65import static android.content.pm.PackageManager.MATCH_ANY_USER;
66import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
67import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
68import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
69import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
70import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
71import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES;
72import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
73import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
74import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL;
75import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
76import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
77import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
78import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
79import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
80import static android.content.pm.PackageManager.PERMISSION_DENIED;
81import static android.content.pm.PackageManager.PERMISSION_GRANTED;
82import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
83import static android.content.pm.PackageParser.isApkFile;
84import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
85import static android.system.OsConstants.O_CREAT;
86import static android.system.OsConstants.O_RDWR;
87import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
88import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
89import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
90import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
91import static com.android.internal.util.ArrayUtils.appendInt;
92import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
93import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
94import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
95import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
96import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
97import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
98import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter;
99import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
100import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
101import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
102import static dalvik.system.DexFile.getNonProfileGuidedCompilerFilter;
103
104import android.Manifest;
105import android.annotation.IntDef;
106import android.annotation.NonNull;
107import android.annotation.Nullable;
108import android.app.ActivityManager;
109import android.app.AppOpsManager;
110import android.app.IActivityManager;
111import android.app.ResourcesManager;
112import android.app.admin.IDevicePolicyManager;
113import android.app.admin.SecurityLog;
114import android.app.backup.IBackupManager;
115import android.content.BroadcastReceiver;
116import android.content.ComponentName;
117import android.content.ContentResolver;
118import android.content.Context;
119import android.content.IIntentReceiver;
120import android.content.Intent;
121import android.content.IntentFilter;
122import android.content.IntentSender;
123import android.content.IntentSender.SendIntentException;
124import android.content.ServiceConnection;
125import android.content.pm.ActivityInfo;
126import android.content.pm.ApplicationInfo;
127import android.content.pm.AppsQueryHelper;
128import android.content.pm.AuxiliaryResolveInfo;
129import android.content.pm.ChangedPackages;
130import android.content.pm.FallbackCategoryProvider;
131import android.content.pm.FeatureInfo;
132import android.content.pm.IOnPermissionsChangeListener;
133import android.content.pm.IPackageDataObserver;
134import android.content.pm.IPackageDeleteObserver;
135import android.content.pm.IPackageDeleteObserver2;
136import android.content.pm.IPackageInstallObserver2;
137import android.content.pm.IPackageInstaller;
138import android.content.pm.IPackageManager;
139import android.content.pm.IPackageMoveObserver;
140import android.content.pm.IPackageStatsObserver;
141import android.content.pm.InstantAppInfo;
142import android.content.pm.InstantAppRequest;
143import android.content.pm.InstantAppResolveInfo;
144import android.content.pm.InstrumentationInfo;
145import android.content.pm.IntentFilterVerificationInfo;
146import android.content.pm.KeySet;
147import android.content.pm.PackageCleanItem;
148import android.content.pm.PackageInfo;
149import android.content.pm.PackageInfoLite;
150import android.content.pm.PackageInstaller;
151import android.content.pm.PackageManager;
152import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
153import android.content.pm.PackageManagerInternal;
154import android.content.pm.PackageParser;
155import android.content.pm.PackageParser.ActivityIntentInfo;
156import android.content.pm.PackageParser.PackageLite;
157import android.content.pm.PackageParser.PackageParserException;
158import android.content.pm.PackageStats;
159import android.content.pm.PackageUserState;
160import android.content.pm.ParceledListSlice;
161import android.content.pm.PermissionGroupInfo;
162import android.content.pm.PermissionInfo;
163import android.content.pm.ProviderInfo;
164import android.content.pm.ResolveInfo;
165import android.content.pm.ServiceInfo;
166import android.content.pm.SharedLibraryInfo;
167import android.content.pm.Signature;
168import android.content.pm.UserInfo;
169import android.content.pm.VerifierDeviceIdentity;
170import android.content.pm.VerifierInfo;
171import android.content.pm.VersionedPackage;
172import android.content.res.Resources;
173import android.database.ContentObserver;
174import android.graphics.Bitmap;
175import android.hardware.display.DisplayManager;
176import android.net.Uri;
177import android.os.Binder;
178import android.os.Build;
179import android.os.Bundle;
180import android.os.Debug;
181import android.os.Environment;
182import android.os.Environment.UserEnvironment;
183import android.os.FileUtils;
184import android.os.Handler;
185import android.os.IBinder;
186import android.os.Looper;
187import android.os.Message;
188import android.os.Parcel;
189import android.os.ParcelFileDescriptor;
190import android.os.PatternMatcher;
191import android.os.Process;
192import android.os.RemoteCallbackList;
193import android.os.RemoteException;
194import android.os.ResultReceiver;
195import android.os.SELinux;
196import android.os.ServiceManager;
197import android.os.ShellCallback;
198import android.os.SystemClock;
199import android.os.SystemProperties;
200import android.os.Trace;
201import android.os.UserHandle;
202import android.os.UserManager;
203import android.os.UserManagerInternal;
204import android.os.storage.IStorageManager;
205import android.os.storage.StorageEventListener;
206import android.os.storage.StorageManager;
207import android.os.storage.StorageManagerInternal;
208import android.os.storage.VolumeInfo;
209import android.os.storage.VolumeRecord;
210import android.provider.Settings.Global;
211import android.provider.Settings.Secure;
212import android.security.KeyStore;
213import android.security.SystemKeyStore;
214import android.service.pm.PackageServiceDumpProto;
215import android.system.ErrnoException;
216import android.system.Os;
217import android.text.TextUtils;
218import android.text.format.DateUtils;
219import android.util.ArrayMap;
220import android.util.ArraySet;
221import android.util.Base64;
222import android.util.BootTimingsTraceLog;
223import android.util.DisplayMetrics;
224import android.util.EventLog;
225import android.util.ExceptionUtils;
226import android.util.Log;
227import android.util.LogPrinter;
228import android.util.MathUtils;
229import android.util.PackageUtils;
230import android.util.Pair;
231import android.util.PrintStreamPrinter;
232import android.util.Slog;
233import android.util.SparseArray;
234import android.util.SparseBooleanArray;
235import android.util.SparseIntArray;
236import android.util.Xml;
237import android.util.jar.StrictJarFile;
238import android.util.proto.ProtoOutputStream;
239import android.view.Display;
240
241import com.android.internal.R;
242import com.android.internal.annotations.GuardedBy;
243import com.android.internal.app.IMediaContainerService;
244import com.android.internal.app.ResolverActivity;
245import com.android.internal.content.NativeLibraryHelper;
246import com.android.internal.content.PackageHelper;
247import com.android.internal.logging.MetricsLogger;
248import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
249import com.android.internal.os.IParcelFileDescriptorFactory;
250import com.android.internal.os.RoSystemProperties;
251import com.android.internal.os.SomeArgs;
252import com.android.internal.os.Zygote;
253import com.android.internal.telephony.CarrierAppUtils;
254import com.android.internal.util.ArrayUtils;
255import com.android.internal.util.ConcurrentUtils;
256import com.android.internal.util.DumpUtils;
257import com.android.internal.util.FastPrintWriter;
258import com.android.internal.util.FastXmlSerializer;
259import com.android.internal.util.IndentingPrintWriter;
260import com.android.internal.util.Preconditions;
261import com.android.internal.util.XmlUtils;
262import com.android.server.AttributeCache;
263import com.android.server.DeviceIdleController;
264import com.android.server.EventLogTags;
265import com.android.server.FgThread;
266import com.android.server.IntentResolver;
267import com.android.server.LocalServices;
268import com.android.server.LockGuard;
269import com.android.server.ServiceThread;
270import com.android.server.SystemConfig;
271import com.android.server.SystemServerInitThreadPool;
272import com.android.server.Watchdog;
273import com.android.server.net.NetworkPolicyManagerInternal;
274import com.android.server.pm.Installer.InstallerException;
275import com.android.server.pm.PermissionsState.PermissionState;
276import com.android.server.pm.Settings.DatabaseVersion;
277import com.android.server.pm.Settings.VersionInfo;
278import com.android.server.pm.dex.DexManager;
279import com.android.server.storage.DeviceStorageMonitorInternal;
280
281import dalvik.system.CloseGuard;
282import dalvik.system.DexFile;
283import dalvik.system.VMRuntime;
284
285import libcore.io.IoUtils;
286import libcore.util.EmptyArray;
287
288import org.xmlpull.v1.XmlPullParser;
289import org.xmlpull.v1.XmlPullParserException;
290import org.xmlpull.v1.XmlSerializer;
291
292import java.io.BufferedOutputStream;
293import java.io.BufferedReader;
294import java.io.ByteArrayInputStream;
295import java.io.ByteArrayOutputStream;
296import java.io.File;
297import java.io.FileDescriptor;
298import java.io.FileInputStream;
299import java.io.FileOutputStream;
300import java.io.FileReader;
301import java.io.FilenameFilter;
302import java.io.IOException;
303import java.io.PrintWriter;
304import java.lang.annotation.Retention;
305import java.lang.annotation.RetentionPolicy;
306import java.nio.charset.StandardCharsets;
307import java.security.DigestInputStream;
308import java.security.MessageDigest;
309import java.security.NoSuchAlgorithmException;
310import java.security.PublicKey;
311import java.security.SecureRandom;
312import java.security.cert.Certificate;
313import java.security.cert.CertificateEncodingException;
314import java.security.cert.CertificateException;
315import java.text.SimpleDateFormat;
316import java.util.ArrayList;
317import java.util.Arrays;
318import java.util.Collection;
319import java.util.Collections;
320import java.util.Comparator;
321import java.util.Date;
322import java.util.HashMap;
323import java.util.HashSet;
324import java.util.Iterator;
325import java.util.List;
326import java.util.Map;
327import java.util.Objects;
328import java.util.Set;
329import java.util.concurrent.CountDownLatch;
330import java.util.concurrent.Future;
331import java.util.concurrent.TimeUnit;
332import java.util.concurrent.atomic.AtomicBoolean;
333import java.util.concurrent.atomic.AtomicInteger;
334
335/**
336 * Keep track of all those APKs everywhere.
337 * <p>
338 * Internally there are two important locks:
339 * <ul>
340 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
341 * and other related state. It is a fine-grained lock that should only be held
342 * momentarily, as it's one of the most contended locks in the system.
343 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
344 * operations typically involve heavy lifting of application data on disk. Since
345 * {@code installd} is single-threaded, and it's operations can often be slow,
346 * this lock should never be acquired while already holding {@link #mPackages}.
347 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
348 * holding {@link #mInstallLock}.
349 * </ul>
350 * Many internal methods rely on the caller to hold the appropriate locks, and
351 * this contract is expressed through method name suffixes:
352 * <ul>
353 * <li>fooLI(): the caller must hold {@link #mInstallLock}
354 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
355 * being modified must be frozen
356 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
357 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
358 * </ul>
359 * <p>
360 * Because this class is very central to the platform's security; please run all
361 * CTS and unit tests whenever making modifications:
362 *
363 * <pre>
364 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
365 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
366 * </pre>
367 */
368public class PackageManagerService extends IPackageManager.Stub
369        implements PackageSender {
370    static final String TAG = "PackageManager";
371    static final boolean DEBUG_SETTINGS = false;
372    static final boolean DEBUG_PREFERRED = false;
373    static final boolean DEBUG_UPGRADE = false;
374    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
375    private static final boolean DEBUG_BACKUP = false;
376    private static final boolean DEBUG_INSTALL = false;
377    private static final boolean DEBUG_REMOVE = false;
378    private static final boolean DEBUG_BROADCASTS = false;
379    private static final boolean DEBUG_SHOW_INFO = false;
380    private static final boolean DEBUG_PACKAGE_INFO = false;
381    private static final boolean DEBUG_INTENT_MATCHING = false;
382    private static final boolean DEBUG_PACKAGE_SCANNING = false;
383    private static final boolean DEBUG_VERIFY = false;
384    private static final boolean DEBUG_FILTERS = false;
385    private static final boolean DEBUG_PERMISSIONS = false;
386    private static final boolean DEBUG_SHARED_LIBRARIES = false;
387
388    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
389    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
390    // user, but by default initialize to this.
391    public static final boolean DEBUG_DEXOPT = false;
392
393    private static final boolean DEBUG_ABI_SELECTION = false;
394    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
395    private static final boolean DEBUG_TRIAGED_MISSING = false;
396    private static final boolean DEBUG_APP_DATA = false;
397
398    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
399    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
400
401    private static final boolean HIDE_EPHEMERAL_APIS = false;
402
403    private static final boolean ENABLE_FREE_CACHE_V2 =
404            SystemProperties.getBoolean("fw.free_cache_v2", true);
405
406    private static final int RADIO_UID = Process.PHONE_UID;
407    private static final int LOG_UID = Process.LOG_UID;
408    private static final int NFC_UID = Process.NFC_UID;
409    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
410    private static final int SHELL_UID = Process.SHELL_UID;
411
412    // Cap the size of permission trees that 3rd party apps can define
413    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
414
415    // Suffix used during package installation when copying/moving
416    // package apks to install directory.
417    private static final String INSTALL_PACKAGE_SUFFIX = "-";
418
419    static final int SCAN_NO_DEX = 1<<1;
420    static final int SCAN_FORCE_DEX = 1<<2;
421    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
422    static final int SCAN_NEW_INSTALL = 1<<4;
423    static final int SCAN_UPDATE_TIME = 1<<5;
424    static final int SCAN_BOOTING = 1<<6;
425    static final int SCAN_TRUSTED_OVERLAY = 1<<7;
426    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8;
427    static final int SCAN_REPLACING = 1<<9;
428    static final int SCAN_REQUIRE_KNOWN = 1<<10;
429    static final int SCAN_MOVE = 1<<11;
430    static final int SCAN_INITIAL = 1<<12;
431    static final int SCAN_CHECK_ONLY = 1<<13;
432    static final int SCAN_DONT_KILL_APP = 1<<14;
433    static final int SCAN_IGNORE_FROZEN = 1<<15;
434    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16;
435    static final int SCAN_AS_INSTANT_APP = 1<<17;
436    static final int SCAN_AS_FULL_APP = 1<<18;
437    /** Should not be with the scan flags */
438    static final int FLAGS_REMOVE_CHATTY = 1<<31;
439
440    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
441
442    private static final int[] EMPTY_INT_ARRAY = new int[0];
443
444    private static final int TYPE_UNKNOWN = 0;
445    private static final int TYPE_ACTIVITY = 1;
446    private static final int TYPE_RECEIVER = 2;
447    private static final int TYPE_SERVICE = 3;
448    private static final int TYPE_PROVIDER = 4;
449    @IntDef(prefix = { "TYPE_" }, value = {
450            TYPE_UNKNOWN,
451            TYPE_ACTIVITY,
452            TYPE_RECEIVER,
453            TYPE_SERVICE,
454            TYPE_PROVIDER,
455    })
456    @Retention(RetentionPolicy.SOURCE)
457    public @interface ComponentType {}
458
459    /**
460     * Timeout (in milliseconds) after which the watchdog should declare that
461     * our handler thread is wedged.  The usual default for such things is one
462     * minute but we sometimes do very lengthy I/O operations on this thread,
463     * such as installing multi-gigabyte applications, so ours needs to be longer.
464     */
465    static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
466
467    /**
468     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
469     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
470     * settings entry if available, otherwise we use the hardcoded default.  If it's been
471     * more than this long since the last fstrim, we force one during the boot sequence.
472     *
473     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
474     * one gets run at the next available charging+idle time.  This final mandatory
475     * no-fstrim check kicks in only of the other scheduling criteria is never met.
476     */
477    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
478
479    /**
480     * Whether verification is enabled by default.
481     */
482    private static final boolean DEFAULT_VERIFY_ENABLE = true;
483
484    /**
485     * The default maximum time to wait for the verification agent to return in
486     * milliseconds.
487     */
488    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
489
490    /**
491     * The default response for package verification timeout.
492     *
493     * This can be either PackageManager.VERIFICATION_ALLOW or
494     * PackageManager.VERIFICATION_REJECT.
495     */
496    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
497
498    static final String PLATFORM_PACKAGE_NAME = "android";
499
500    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
501
502    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
503            DEFAULT_CONTAINER_PACKAGE,
504            "com.android.defcontainer.DefaultContainerService");
505
506    private static final String KILL_APP_REASON_GIDS_CHANGED =
507            "permission grant or revoke changed gids";
508
509    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
510            "permissions revoked";
511
512    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
513
514    private static final String PACKAGE_SCHEME = "package";
515
516    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
517
518    /** Permission grant: not grant the permission. */
519    private static final int GRANT_DENIED = 1;
520
521    /** Permission grant: grant the permission as an install permission. */
522    private static final int GRANT_INSTALL = 2;
523
524    /** Permission grant: grant the permission as a runtime one. */
525    private static final int GRANT_RUNTIME = 3;
526
527    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
528    private static final int GRANT_UPGRADE = 4;
529
530    /** Canonical intent used to identify what counts as a "web browser" app */
531    private static final Intent sBrowserIntent;
532    static {
533        sBrowserIntent = new Intent();
534        sBrowserIntent.setAction(Intent.ACTION_VIEW);
535        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
536        sBrowserIntent.setData(Uri.parse("http:"));
537    }
538
539    /**
540     * The set of all protected actions [i.e. those actions for which a high priority
541     * intent filter is disallowed].
542     */
543    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
544    static {
545        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
546        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
547        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
548        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
549    }
550
551    // Compilation reasons.
552    public static final int REASON_FIRST_BOOT = 0;
553    public static final int REASON_BOOT = 1;
554    public static final int REASON_INSTALL = 2;
555    public static final int REASON_BACKGROUND_DEXOPT = 3;
556    public static final int REASON_AB_OTA = 4;
557
558    public static final int REASON_LAST = REASON_AB_OTA;
559
560    /** All dangerous permission names in the same order as the events in MetricsEvent */
561    private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList(
562            Manifest.permission.READ_CALENDAR,
563            Manifest.permission.WRITE_CALENDAR,
564            Manifest.permission.CAMERA,
565            Manifest.permission.READ_CONTACTS,
566            Manifest.permission.WRITE_CONTACTS,
567            Manifest.permission.GET_ACCOUNTS,
568            Manifest.permission.ACCESS_FINE_LOCATION,
569            Manifest.permission.ACCESS_COARSE_LOCATION,
570            Manifest.permission.RECORD_AUDIO,
571            Manifest.permission.READ_PHONE_STATE,
572            Manifest.permission.CALL_PHONE,
573            Manifest.permission.READ_CALL_LOG,
574            Manifest.permission.WRITE_CALL_LOG,
575            Manifest.permission.ADD_VOICEMAIL,
576            Manifest.permission.USE_SIP,
577            Manifest.permission.PROCESS_OUTGOING_CALLS,
578            Manifest.permission.READ_CELL_BROADCASTS,
579            Manifest.permission.BODY_SENSORS,
580            Manifest.permission.SEND_SMS,
581            Manifest.permission.RECEIVE_SMS,
582            Manifest.permission.READ_SMS,
583            Manifest.permission.RECEIVE_WAP_PUSH,
584            Manifest.permission.RECEIVE_MMS,
585            Manifest.permission.READ_EXTERNAL_STORAGE,
586            Manifest.permission.WRITE_EXTERNAL_STORAGE,
587            Manifest.permission.READ_PHONE_NUMBERS,
588            Manifest.permission.ANSWER_PHONE_CALLS);
589
590
591    /**
592     * Version number for the package parser cache. Increment this whenever the format or
593     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
594     */
595    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
596
597    /**
598     * Whether the package parser cache is enabled.
599     */
600    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
601
602    final ServiceThread mHandlerThread;
603
604    final PackageHandler mHandler;
605
606    private final ProcessLoggingHandler mProcessLoggingHandler;
607
608    /**
609     * Messages for {@link #mHandler} that need to wait for system ready before
610     * being dispatched.
611     */
612    private ArrayList<Message> mPostSystemReadyMessages;
613
614    final int mSdkVersion = Build.VERSION.SDK_INT;
615
616    final Context mContext;
617    final boolean mFactoryTest;
618    final boolean mOnlyCore;
619    final DisplayMetrics mMetrics;
620    final int mDefParseFlags;
621    final String[] mSeparateProcesses;
622    final boolean mIsUpgrade;
623    final boolean mIsPreNUpgrade;
624    final boolean mIsPreNMR1Upgrade;
625
626    // Have we told the Activity Manager to whitelist the default container service by uid yet?
627    @GuardedBy("mPackages")
628    boolean mDefaultContainerWhitelisted = false;
629
630    @GuardedBy("mPackages")
631    private boolean mDexOptDialogShown;
632
633    /** The location for ASEC container files on internal storage. */
634    final String mAsecInternalPath;
635
636    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
637    // LOCK HELD.  Can be called with mInstallLock held.
638    @GuardedBy("mInstallLock")
639    final Installer mInstaller;
640
641    /** Directory where installed third-party apps stored */
642    final File mAppInstallDir;
643
644    /**
645     * Directory to which applications installed internally have their
646     * 32 bit native libraries copied.
647     */
648    private File mAppLib32InstallDir;
649
650    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
651    // apps.
652    final File mDrmAppPrivateInstallDir;
653
654    // ----------------------------------------------------------------
655
656    // Lock for state used when installing and doing other long running
657    // operations.  Methods that must be called with this lock held have
658    // the suffix "LI".
659    final Object mInstallLock = new Object();
660
661    // ----------------------------------------------------------------
662
663    // Keys are String (package name), values are Package.  This also serves
664    // as the lock for the global state.  Methods that must be called with
665    // this lock held have the prefix "LP".
666    @GuardedBy("mPackages")
667    final ArrayMap<String, PackageParser.Package> mPackages =
668            new ArrayMap<String, PackageParser.Package>();
669
670    final ArrayMap<String, Set<String>> mKnownCodebase =
671            new ArrayMap<String, Set<String>>();
672
673    // Keys are isolated uids and values are the uid of the application
674    // that created the isolated proccess.
675    @GuardedBy("mPackages")
676    final SparseIntArray mIsolatedOwners = new SparseIntArray();
677
678    /**
679     * Tracks new system packages [received in an OTA] that we expect to
680     * find updated user-installed versions. Keys are package name, values
681     * are package location.
682     */
683    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
684    /**
685     * Tracks high priority intent filters for protected actions. During boot, certain
686     * filter actions are protected and should never be allowed to have a high priority
687     * intent filter for them. However, there is one, and only one exception -- the
688     * setup wizard. It must be able to define a high priority intent filter for these
689     * actions to ensure there are no escapes from the wizard. We need to delay processing
690     * of these during boot as we need to look at all of the system packages in order
691     * to know which component is the setup wizard.
692     */
693    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
694    /**
695     * Whether or not processing protected filters should be deferred.
696     */
697    private boolean mDeferProtectedFilters = true;
698
699    /**
700     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
701     */
702    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
703    /**
704     * Whether or not system app permissions should be promoted from install to runtime.
705     */
706    boolean mPromoteSystemApps;
707
708    @GuardedBy("mPackages")
709    final Settings mSettings;
710
711    /**
712     * Set of package names that are currently "frozen", which means active
713     * surgery is being done on the code/data for that package. The platform
714     * will refuse to launch frozen packages to avoid race conditions.
715     *
716     * @see PackageFreezer
717     */
718    @GuardedBy("mPackages")
719    final ArraySet<String> mFrozenPackages = new ArraySet<>();
720
721    final ProtectedPackages mProtectedPackages;
722
723    boolean mFirstBoot;
724
725    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
726
727    // System configuration read by SystemConfig.
728    final int[] mGlobalGids;
729    final SparseArray<ArraySet<String>> mSystemPermissions;
730    @GuardedBy("mAvailableFeatures")
731    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
732
733    // If mac_permissions.xml was found for seinfo labeling.
734    boolean mFoundPolicyFile;
735
736    private final InstantAppRegistry mInstantAppRegistry;
737
738    @GuardedBy("mPackages")
739    int mChangedPackagesSequenceNumber;
740    /**
741     * List of changed [installed, removed or updated] packages.
742     * mapping from user id -> sequence number -> package name
743     */
744    @GuardedBy("mPackages")
745    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
746    /**
747     * The sequence number of the last change to a package.
748     * mapping from user id -> package name -> sequence number
749     */
750    @GuardedBy("mPackages")
751    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
752
753    class PackageParserCallback implements PackageParser.Callback {
754        @Override public final boolean hasFeature(String feature) {
755            return PackageManagerService.this.hasSystemFeature(feature, 0);
756        }
757
758        final List<PackageParser.Package> getStaticOverlayPackagesLocked(
759                Collection<PackageParser.Package> allPackages, String targetPackageName) {
760            List<PackageParser.Package> overlayPackages = null;
761            for (PackageParser.Package p : allPackages) {
762                if (targetPackageName.equals(p.mOverlayTarget) && p.mIsStaticOverlay) {
763                    if (overlayPackages == null) {
764                        overlayPackages = new ArrayList<PackageParser.Package>();
765                    }
766                    overlayPackages.add(p);
767                }
768            }
769            if (overlayPackages != null) {
770                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
771                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
772                        return p1.mOverlayPriority - p2.mOverlayPriority;
773                    }
774                };
775                Collections.sort(overlayPackages, cmp);
776            }
777            return overlayPackages;
778        }
779
780        final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages,
781                String targetPackageName, String targetPath) {
782            if ("android".equals(targetPackageName)) {
783                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
784                // native AssetManager.
785                return null;
786            }
787            List<PackageParser.Package> overlayPackages =
788                    getStaticOverlayPackagesLocked(allPackages, targetPackageName);
789            if (overlayPackages == null || overlayPackages.isEmpty()) {
790                return null;
791            }
792            List<String> overlayPathList = null;
793            for (PackageParser.Package overlayPackage : overlayPackages) {
794                if (targetPath == null) {
795                    if (overlayPathList == null) {
796                        overlayPathList = new ArrayList<String>();
797                    }
798                    overlayPathList.add(overlayPackage.baseCodePath);
799                    continue;
800                }
801
802                try {
803                    // Creates idmaps for system to parse correctly the Android manifest of the
804                    // target package.
805                    //
806                    // OverlayManagerService will update each of them with a correct gid from its
807                    // target package app id.
808                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
809                            UserHandle.getSharedAppGid(
810                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
811                    if (overlayPathList == null) {
812                        overlayPathList = new ArrayList<String>();
813                    }
814                    overlayPathList.add(overlayPackage.baseCodePath);
815                } catch (InstallerException e) {
816                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
817                            overlayPackage.baseCodePath);
818                }
819            }
820            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
821        }
822
823        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
824            synchronized (mPackages) {
825                return getStaticOverlayPathsLocked(
826                        mPackages.values(), targetPackageName, targetPath);
827            }
828        }
829
830        @Override public final String[] getOverlayApks(String targetPackageName) {
831            return getStaticOverlayPaths(targetPackageName, null);
832        }
833
834        @Override public final String[] getOverlayPaths(String targetPackageName,
835                String targetPath) {
836            return getStaticOverlayPaths(targetPackageName, targetPath);
837        }
838    };
839
840    class ParallelPackageParserCallback extends PackageParserCallback {
841        List<PackageParser.Package> mOverlayPackages = null;
842
843        void findStaticOverlayPackages() {
844            synchronized (mPackages) {
845                for (PackageParser.Package p : mPackages.values()) {
846                    if (p.mIsStaticOverlay) {
847                        if (mOverlayPackages == null) {
848                            mOverlayPackages = new ArrayList<PackageParser.Package>();
849                        }
850                        mOverlayPackages.add(p);
851                    }
852                }
853            }
854        }
855
856        @Override
857        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
858            // We can trust mOverlayPackages without holding mPackages because package uninstall
859            // can't happen while running parallel parsing.
860            // Moreover holding mPackages on each parsing thread causes dead-lock.
861            return mOverlayPackages == null ? null :
862                    getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath);
863        }
864    }
865
866    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
867    final ParallelPackageParserCallback mParallelPackageParserCallback =
868            new ParallelPackageParserCallback();
869
870    public static final class SharedLibraryEntry {
871        public final @Nullable String path;
872        public final @Nullable String apk;
873        public final @NonNull SharedLibraryInfo info;
874
875        SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
876                String declaringPackageName, int declaringPackageVersionCode) {
877            path = _path;
878            apk = _apk;
879            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
880                    declaringPackageName, declaringPackageVersionCode), null);
881        }
882    }
883
884    // Currently known shared libraries.
885    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
886    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
887            new ArrayMap<>();
888
889    // All available activities, for your resolving pleasure.
890    final ActivityIntentResolver mActivities =
891            new ActivityIntentResolver();
892
893    // All available receivers, for your resolving pleasure.
894    final ActivityIntentResolver mReceivers =
895            new ActivityIntentResolver();
896
897    // All available services, for your resolving pleasure.
898    final ServiceIntentResolver mServices = new ServiceIntentResolver();
899
900    // All available providers, for your resolving pleasure.
901    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
902
903    // Mapping from provider base names (first directory in content URI codePath)
904    // to the provider information.
905    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
906            new ArrayMap<String, PackageParser.Provider>();
907
908    // Mapping from instrumentation class names to info about them.
909    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
910            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
911
912    // Mapping from permission names to info about them.
913    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
914            new ArrayMap<String, PackageParser.PermissionGroup>();
915
916    // Packages whose data we have transfered into another package, thus
917    // should no longer exist.
918    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
919
920    // Broadcast actions that are only available to the system.
921    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
922
923    /** List of packages waiting for verification. */
924    final SparseArray<PackageVerificationState> mPendingVerification
925            = new SparseArray<PackageVerificationState>();
926
927    /** Set of packages associated with each app op permission. */
928    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
929
930    final PackageInstallerService mInstallerService;
931
932    private final PackageDexOptimizer mPackageDexOptimizer;
933    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
934    // is used by other apps).
935    private final DexManager mDexManager;
936
937    private AtomicInteger mNextMoveId = new AtomicInteger();
938    private final MoveCallbacks mMoveCallbacks;
939
940    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
941
942    // Cache of users who need badging.
943    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
944
945    /** Token for keys in mPendingVerification. */
946    private int mPendingVerificationToken = 0;
947
948    volatile boolean mSystemReady;
949    volatile boolean mSafeMode;
950    volatile boolean mHasSystemUidErrors;
951    private volatile boolean mEphemeralAppsDisabled;
952
953    ApplicationInfo mAndroidApplication;
954    final ActivityInfo mResolveActivity = new ActivityInfo();
955    final ResolveInfo mResolveInfo = new ResolveInfo();
956    ComponentName mResolveComponentName;
957    PackageParser.Package mPlatformPackage;
958    ComponentName mCustomResolverComponentName;
959
960    boolean mResolverReplaced = false;
961
962    private final @Nullable ComponentName mIntentFilterVerifierComponent;
963    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
964
965    private int mIntentFilterVerificationToken = 0;
966
967    /** The service connection to the ephemeral resolver */
968    final EphemeralResolverConnection mInstantAppResolverConnection;
969    /** Component used to show resolver settings for Instant Apps */
970    final ComponentName mInstantAppResolverSettingsComponent;
971
972    /** Activity used to install instant applications */
973    ActivityInfo mInstantAppInstallerActivity;
974    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
975
976    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
977            = new SparseArray<IntentFilterVerificationState>();
978
979    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
980
981    // List of packages names to keep cached, even if they are uninstalled for all users
982    private List<String> mKeepUninstalledPackages;
983
984    private UserManagerInternal mUserManagerInternal;
985
986    private DeviceIdleController.LocalService mDeviceIdleController;
987
988    private File mCacheDir;
989
990    private ArraySet<String> mPrivappPermissionsViolations;
991
992    private Future<?> mPrepareAppDataFuture;
993
994    private static class IFVerificationParams {
995        PackageParser.Package pkg;
996        boolean replacing;
997        int userId;
998        int verifierUid;
999
1000        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1001                int _userId, int _verifierUid) {
1002            pkg = _pkg;
1003            replacing = _replacing;
1004            userId = _userId;
1005            replacing = _replacing;
1006            verifierUid = _verifierUid;
1007        }
1008    }
1009
1010    private interface IntentFilterVerifier<T extends IntentFilter> {
1011        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1012                                               T filter, String packageName);
1013        void startVerifications(int userId);
1014        void receiveVerificationResponse(int verificationId);
1015    }
1016
1017    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1018        private Context mContext;
1019        private ComponentName mIntentFilterVerifierComponent;
1020        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1021
1022        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1023            mContext = context;
1024            mIntentFilterVerifierComponent = verifierComponent;
1025        }
1026
1027        private String getDefaultScheme() {
1028            return IntentFilter.SCHEME_HTTPS;
1029        }
1030
1031        @Override
1032        public void startVerifications(int userId) {
1033            // Launch verifications requests
1034            int count = mCurrentIntentFilterVerifications.size();
1035            for (int n=0; n<count; n++) {
1036                int verificationId = mCurrentIntentFilterVerifications.get(n);
1037                final IntentFilterVerificationState ivs =
1038                        mIntentFilterVerificationStates.get(verificationId);
1039
1040                String packageName = ivs.getPackageName();
1041
1042                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1043                final int filterCount = filters.size();
1044                ArraySet<String> domainsSet = new ArraySet<>();
1045                for (int m=0; m<filterCount; m++) {
1046                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1047                    domainsSet.addAll(filter.getHostsList());
1048                }
1049                synchronized (mPackages) {
1050                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1051                            packageName, domainsSet) != null) {
1052                        scheduleWriteSettingsLocked();
1053                    }
1054                }
1055                sendVerificationRequest(userId, verificationId, ivs);
1056            }
1057            mCurrentIntentFilterVerifications.clear();
1058        }
1059
1060        private void sendVerificationRequest(int userId, int verificationId,
1061                IntentFilterVerificationState ivs) {
1062
1063            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1064            verificationIntent.putExtra(
1065                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1066                    verificationId);
1067            verificationIntent.putExtra(
1068                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1069                    getDefaultScheme());
1070            verificationIntent.putExtra(
1071                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1072                    ivs.getHostsString());
1073            verificationIntent.putExtra(
1074                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1075                    ivs.getPackageName());
1076            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1077            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1078
1079            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1080            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1081                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1082                    userId, false, "intent filter verifier");
1083
1084            UserHandle user = new UserHandle(userId);
1085            mContext.sendBroadcastAsUser(verificationIntent, user);
1086            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1087                    "Sending IntentFilter verification broadcast");
1088        }
1089
1090        public void receiveVerificationResponse(int verificationId) {
1091            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1092
1093            final boolean verified = ivs.isVerified();
1094
1095            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1096            final int count = filters.size();
1097            if (DEBUG_DOMAIN_VERIFICATION) {
1098                Slog.i(TAG, "Received verification response " + verificationId
1099                        + " for " + count + " filters, verified=" + verified);
1100            }
1101            for (int n=0; n<count; n++) {
1102                PackageParser.ActivityIntentInfo filter = filters.get(n);
1103                filter.setVerified(verified);
1104
1105                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1106                        + " verified with result:" + verified + " and hosts:"
1107                        + ivs.getHostsString());
1108            }
1109
1110            mIntentFilterVerificationStates.remove(verificationId);
1111
1112            final String packageName = ivs.getPackageName();
1113            IntentFilterVerificationInfo ivi = null;
1114
1115            synchronized (mPackages) {
1116                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1117            }
1118            if (ivi == null) {
1119                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1120                        + verificationId + " packageName:" + packageName);
1121                return;
1122            }
1123            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1124                    "Updating IntentFilterVerificationInfo for package " + packageName
1125                            +" verificationId:" + verificationId);
1126
1127            synchronized (mPackages) {
1128                if (verified) {
1129                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1130                } else {
1131                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1132                }
1133                scheduleWriteSettingsLocked();
1134
1135                final int userId = ivs.getUserId();
1136                if (userId != UserHandle.USER_ALL) {
1137                    final int userStatus =
1138                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1139
1140                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1141                    boolean needUpdate = false;
1142
1143                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1144                    // already been set by the User thru the Disambiguation dialog
1145                    switch (userStatus) {
1146                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1147                            if (verified) {
1148                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1149                            } else {
1150                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1151                            }
1152                            needUpdate = true;
1153                            break;
1154
1155                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1156                            if (verified) {
1157                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1158                                needUpdate = true;
1159                            }
1160                            break;
1161
1162                        default:
1163                            // Nothing to do
1164                    }
1165
1166                    if (needUpdate) {
1167                        mSettings.updateIntentFilterVerificationStatusLPw(
1168                                packageName, updatedStatus, userId);
1169                        scheduleWritePackageRestrictionsLocked(userId);
1170                    }
1171                }
1172            }
1173        }
1174
1175        @Override
1176        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1177                    ActivityIntentInfo filter, String packageName) {
1178            if (!hasValidDomains(filter)) {
1179                return false;
1180            }
1181            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1182            if (ivs == null) {
1183                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1184                        packageName);
1185            }
1186            if (DEBUG_DOMAIN_VERIFICATION) {
1187                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1188            }
1189            ivs.addFilter(filter);
1190            return true;
1191        }
1192
1193        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1194                int userId, int verificationId, String packageName) {
1195            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1196                    verifierUid, userId, packageName);
1197            ivs.setPendingState();
1198            synchronized (mPackages) {
1199                mIntentFilterVerificationStates.append(verificationId, ivs);
1200                mCurrentIntentFilterVerifications.add(verificationId);
1201            }
1202            return ivs;
1203        }
1204    }
1205
1206    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1207        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1208                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1209                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1210    }
1211
1212    // Set of pending broadcasts for aggregating enable/disable of components.
1213    static class PendingPackageBroadcasts {
1214        // for each user id, a map of <package name -> components within that package>
1215        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1216
1217        public PendingPackageBroadcasts() {
1218            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1219        }
1220
1221        public ArrayList<String> get(int userId, String packageName) {
1222            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1223            return packages.get(packageName);
1224        }
1225
1226        public void put(int userId, String packageName, ArrayList<String> components) {
1227            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1228            packages.put(packageName, components);
1229        }
1230
1231        public void remove(int userId, String packageName) {
1232            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1233            if (packages != null) {
1234                packages.remove(packageName);
1235            }
1236        }
1237
1238        public void remove(int userId) {
1239            mUidMap.remove(userId);
1240        }
1241
1242        public int userIdCount() {
1243            return mUidMap.size();
1244        }
1245
1246        public int userIdAt(int n) {
1247            return mUidMap.keyAt(n);
1248        }
1249
1250        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1251            return mUidMap.get(userId);
1252        }
1253
1254        public int size() {
1255            // total number of pending broadcast entries across all userIds
1256            int num = 0;
1257            for (int i = 0; i< mUidMap.size(); i++) {
1258                num += mUidMap.valueAt(i).size();
1259            }
1260            return num;
1261        }
1262
1263        public void clear() {
1264            mUidMap.clear();
1265        }
1266
1267        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1268            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1269            if (map == null) {
1270                map = new ArrayMap<String, ArrayList<String>>();
1271                mUidMap.put(userId, map);
1272            }
1273            return map;
1274        }
1275    }
1276    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1277
1278    // Service Connection to remote media container service to copy
1279    // package uri's from external media onto secure containers
1280    // or internal storage.
1281    private IMediaContainerService mContainerService = null;
1282
1283    static final int SEND_PENDING_BROADCAST = 1;
1284    static final int MCS_BOUND = 3;
1285    static final int END_COPY = 4;
1286    static final int INIT_COPY = 5;
1287    static final int MCS_UNBIND = 6;
1288    static final int START_CLEANING_PACKAGE = 7;
1289    static final int FIND_INSTALL_LOC = 8;
1290    static final int POST_INSTALL = 9;
1291    static final int MCS_RECONNECT = 10;
1292    static final int MCS_GIVE_UP = 11;
1293    static final int UPDATED_MEDIA_STATUS = 12;
1294    static final int WRITE_SETTINGS = 13;
1295    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1296    static final int PACKAGE_VERIFIED = 15;
1297    static final int CHECK_PENDING_VERIFICATION = 16;
1298    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1299    static final int INTENT_FILTER_VERIFIED = 18;
1300    static final int WRITE_PACKAGE_LIST = 19;
1301    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1302
1303    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1304
1305    // Delay time in millisecs
1306    static final int BROADCAST_DELAY = 10 * 1000;
1307
1308    private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1309            2 * 60 * 60 * 1000L; /* two hours */
1310
1311    static UserManagerService sUserManager;
1312
1313    // Stores a list of users whose package restrictions file needs to be updated
1314    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1315
1316    final private DefaultContainerConnection mDefContainerConn =
1317            new DefaultContainerConnection();
1318    class DefaultContainerConnection implements ServiceConnection {
1319        public void onServiceConnected(ComponentName name, IBinder service) {
1320            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1321            final IMediaContainerService imcs = IMediaContainerService.Stub
1322                    .asInterface(Binder.allowBlocking(service));
1323            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1324        }
1325
1326        public void onServiceDisconnected(ComponentName name) {
1327            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1328        }
1329    }
1330
1331    // Recordkeeping of restore-after-install operations that are currently in flight
1332    // between the Package Manager and the Backup Manager
1333    static class PostInstallData {
1334        public InstallArgs args;
1335        public PackageInstalledInfo res;
1336
1337        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1338            args = _a;
1339            res = _r;
1340        }
1341    }
1342
1343    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1344    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1345
1346    // XML tags for backup/restore of various bits of state
1347    private static final String TAG_PREFERRED_BACKUP = "pa";
1348    private static final String TAG_DEFAULT_APPS = "da";
1349    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1350
1351    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1352    private static final String TAG_ALL_GRANTS = "rt-grants";
1353    private static final String TAG_GRANT = "grant";
1354    private static final String ATTR_PACKAGE_NAME = "pkg";
1355
1356    private static final String TAG_PERMISSION = "perm";
1357    private static final String ATTR_PERMISSION_NAME = "name";
1358    private static final String ATTR_IS_GRANTED = "g";
1359    private static final String ATTR_USER_SET = "set";
1360    private static final String ATTR_USER_FIXED = "fixed";
1361    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1362
1363    // System/policy permission grants are not backed up
1364    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1365            FLAG_PERMISSION_POLICY_FIXED
1366            | FLAG_PERMISSION_SYSTEM_FIXED
1367            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1368
1369    // And we back up these user-adjusted states
1370    private static final int USER_RUNTIME_GRANT_MASK =
1371            FLAG_PERMISSION_USER_SET
1372            | FLAG_PERMISSION_USER_FIXED
1373            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1374
1375    final @Nullable String mRequiredVerifierPackage;
1376    final @NonNull String mRequiredInstallerPackage;
1377    final @NonNull String mRequiredUninstallerPackage;
1378    final @Nullable String mSetupWizardPackage;
1379    final @Nullable String mStorageManagerPackage;
1380    final @NonNull String mServicesSystemSharedLibraryPackageName;
1381    final @NonNull String mSharedSystemSharedLibraryPackageName;
1382
1383    final boolean mPermissionReviewRequired;
1384
1385    private final PackageUsage mPackageUsage = new PackageUsage();
1386    private final CompilerStats mCompilerStats = new CompilerStats();
1387
1388    class PackageHandler extends Handler {
1389        private boolean mBound = false;
1390        final ArrayList<HandlerParams> mPendingInstalls =
1391            new ArrayList<HandlerParams>();
1392
1393        private boolean connectToService() {
1394            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1395                    " DefaultContainerService");
1396            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1397            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1398            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1399                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1400                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1401                mBound = true;
1402                return true;
1403            }
1404            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1405            return false;
1406        }
1407
1408        private void disconnectService() {
1409            mContainerService = null;
1410            mBound = false;
1411            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1412            mContext.unbindService(mDefContainerConn);
1413            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1414        }
1415
1416        PackageHandler(Looper looper) {
1417            super(looper);
1418        }
1419
1420        public void handleMessage(Message msg) {
1421            try {
1422                doHandleMessage(msg);
1423            } finally {
1424                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1425            }
1426        }
1427
1428        void doHandleMessage(Message msg) {
1429            switch (msg.what) {
1430                case INIT_COPY: {
1431                    HandlerParams params = (HandlerParams) msg.obj;
1432                    int idx = mPendingInstalls.size();
1433                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1434                    // If a bind was already initiated we dont really
1435                    // need to do anything. The pending install
1436                    // will be processed later on.
1437                    if (!mBound) {
1438                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1439                                System.identityHashCode(mHandler));
1440                        // If this is the only one pending we might
1441                        // have to bind to the service again.
1442                        if (!connectToService()) {
1443                            Slog.e(TAG, "Failed to bind to media container service");
1444                            params.serviceError();
1445                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1446                                    System.identityHashCode(mHandler));
1447                            if (params.traceMethod != null) {
1448                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1449                                        params.traceCookie);
1450                            }
1451                            return;
1452                        } else {
1453                            // Once we bind to the service, the first
1454                            // pending request will be processed.
1455                            mPendingInstalls.add(idx, params);
1456                        }
1457                    } else {
1458                        mPendingInstalls.add(idx, params);
1459                        // Already bound to the service. Just make
1460                        // sure we trigger off processing the first request.
1461                        if (idx == 0) {
1462                            mHandler.sendEmptyMessage(MCS_BOUND);
1463                        }
1464                    }
1465                    break;
1466                }
1467                case MCS_BOUND: {
1468                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1469                    if (msg.obj != null) {
1470                        mContainerService = (IMediaContainerService) msg.obj;
1471                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1472                                System.identityHashCode(mHandler));
1473                    }
1474                    if (mContainerService == null) {
1475                        if (!mBound) {
1476                            // Something seriously wrong since we are not bound and we are not
1477                            // waiting for connection. Bail out.
1478                            Slog.e(TAG, "Cannot bind to media container service");
1479                            for (HandlerParams params : mPendingInstalls) {
1480                                // Indicate service bind error
1481                                params.serviceError();
1482                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1483                                        System.identityHashCode(params));
1484                                if (params.traceMethod != null) {
1485                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1486                                            params.traceMethod, params.traceCookie);
1487                                }
1488                                return;
1489                            }
1490                            mPendingInstalls.clear();
1491                        } else {
1492                            Slog.w(TAG, "Waiting to connect to media container service");
1493                        }
1494                    } else if (mPendingInstalls.size() > 0) {
1495                        HandlerParams params = mPendingInstalls.get(0);
1496                        if (params != null) {
1497                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1498                                    System.identityHashCode(params));
1499                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1500                            if (params.startCopy()) {
1501                                // We are done...  look for more work or to
1502                                // go idle.
1503                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1504                                        "Checking for more work or unbind...");
1505                                // Delete pending install
1506                                if (mPendingInstalls.size() > 0) {
1507                                    mPendingInstalls.remove(0);
1508                                }
1509                                if (mPendingInstalls.size() == 0) {
1510                                    if (mBound) {
1511                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1512                                                "Posting delayed MCS_UNBIND");
1513                                        removeMessages(MCS_UNBIND);
1514                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1515                                        // Unbind after a little delay, to avoid
1516                                        // continual thrashing.
1517                                        sendMessageDelayed(ubmsg, 10000);
1518                                    }
1519                                } else {
1520                                    // There are more pending requests in queue.
1521                                    // Just post MCS_BOUND message to trigger processing
1522                                    // of next pending install.
1523                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1524                                            "Posting MCS_BOUND for next work");
1525                                    mHandler.sendEmptyMessage(MCS_BOUND);
1526                                }
1527                            }
1528                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1529                        }
1530                    } else {
1531                        // Should never happen ideally.
1532                        Slog.w(TAG, "Empty queue");
1533                    }
1534                    break;
1535                }
1536                case MCS_RECONNECT: {
1537                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1538                    if (mPendingInstalls.size() > 0) {
1539                        if (mBound) {
1540                            disconnectService();
1541                        }
1542                        if (!connectToService()) {
1543                            Slog.e(TAG, "Failed to bind to media container service");
1544                            for (HandlerParams params : mPendingInstalls) {
1545                                // Indicate service bind error
1546                                params.serviceError();
1547                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1548                                        System.identityHashCode(params));
1549                            }
1550                            mPendingInstalls.clear();
1551                        }
1552                    }
1553                    break;
1554                }
1555                case MCS_UNBIND: {
1556                    // If there is no actual work left, then time to unbind.
1557                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1558
1559                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1560                        if (mBound) {
1561                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1562
1563                            disconnectService();
1564                        }
1565                    } else if (mPendingInstalls.size() > 0) {
1566                        // There are more pending requests in queue.
1567                        // Just post MCS_BOUND message to trigger processing
1568                        // of next pending install.
1569                        mHandler.sendEmptyMessage(MCS_BOUND);
1570                    }
1571
1572                    break;
1573                }
1574                case MCS_GIVE_UP: {
1575                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1576                    HandlerParams params = mPendingInstalls.remove(0);
1577                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1578                            System.identityHashCode(params));
1579                    break;
1580                }
1581                case SEND_PENDING_BROADCAST: {
1582                    String packages[];
1583                    ArrayList<String> components[];
1584                    int size = 0;
1585                    int uids[];
1586                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1587                    synchronized (mPackages) {
1588                        if (mPendingBroadcasts == null) {
1589                            return;
1590                        }
1591                        size = mPendingBroadcasts.size();
1592                        if (size <= 0) {
1593                            // Nothing to be done. Just return
1594                            return;
1595                        }
1596                        packages = new String[size];
1597                        components = new ArrayList[size];
1598                        uids = new int[size];
1599                        int i = 0;  // filling out the above arrays
1600
1601                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1602                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1603                            Iterator<Map.Entry<String, ArrayList<String>>> it
1604                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1605                                            .entrySet().iterator();
1606                            while (it.hasNext() && i < size) {
1607                                Map.Entry<String, ArrayList<String>> ent = it.next();
1608                                packages[i] = ent.getKey();
1609                                components[i] = ent.getValue();
1610                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1611                                uids[i] = (ps != null)
1612                                        ? UserHandle.getUid(packageUserId, ps.appId)
1613                                        : -1;
1614                                i++;
1615                            }
1616                        }
1617                        size = i;
1618                        mPendingBroadcasts.clear();
1619                    }
1620                    // Send broadcasts
1621                    for (int i = 0; i < size; i++) {
1622                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1623                    }
1624                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1625                    break;
1626                }
1627                case START_CLEANING_PACKAGE: {
1628                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1629                    final String packageName = (String)msg.obj;
1630                    final int userId = msg.arg1;
1631                    final boolean andCode = msg.arg2 != 0;
1632                    synchronized (mPackages) {
1633                        if (userId == UserHandle.USER_ALL) {
1634                            int[] users = sUserManager.getUserIds();
1635                            for (int user : users) {
1636                                mSettings.addPackageToCleanLPw(
1637                                        new PackageCleanItem(user, packageName, andCode));
1638                            }
1639                        } else {
1640                            mSettings.addPackageToCleanLPw(
1641                                    new PackageCleanItem(userId, packageName, andCode));
1642                        }
1643                    }
1644                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1645                    startCleaningPackages();
1646                } break;
1647                case POST_INSTALL: {
1648                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1649
1650                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1651                    final boolean didRestore = (msg.arg2 != 0);
1652                    mRunningInstalls.delete(msg.arg1);
1653
1654                    if (data != null) {
1655                        InstallArgs args = data.args;
1656                        PackageInstalledInfo parentRes = data.res;
1657
1658                        final boolean grantPermissions = (args.installFlags
1659                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1660                        final boolean killApp = (args.installFlags
1661                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1662                        final String[] grantedPermissions = args.installGrantPermissions;
1663
1664                        // Handle the parent package
1665                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1666                                grantedPermissions, didRestore, args.installerPackageName,
1667                                args.observer);
1668
1669                        // Handle the child packages
1670                        final int childCount = (parentRes.addedChildPackages != null)
1671                                ? parentRes.addedChildPackages.size() : 0;
1672                        for (int i = 0; i < childCount; i++) {
1673                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1674                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1675                                    grantedPermissions, false, args.installerPackageName,
1676                                    args.observer);
1677                        }
1678
1679                        // Log tracing if needed
1680                        if (args.traceMethod != null) {
1681                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1682                                    args.traceCookie);
1683                        }
1684                    } else {
1685                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1686                    }
1687
1688                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1689                } break;
1690                case UPDATED_MEDIA_STATUS: {
1691                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1692                    boolean reportStatus = msg.arg1 == 1;
1693                    boolean doGc = msg.arg2 == 1;
1694                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1695                    if (doGc) {
1696                        // Force a gc to clear up stale containers.
1697                        Runtime.getRuntime().gc();
1698                    }
1699                    if (msg.obj != null) {
1700                        @SuppressWarnings("unchecked")
1701                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1702                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1703                        // Unload containers
1704                        unloadAllContainers(args);
1705                    }
1706                    if (reportStatus) {
1707                        try {
1708                            if (DEBUG_SD_INSTALL) Log.i(TAG,
1709                                    "Invoking StorageManagerService call back");
1710                            PackageHelper.getStorageManager().finishMediaUpdate();
1711                        } catch (RemoteException e) {
1712                            Log.e(TAG, "StorageManagerService not running?");
1713                        }
1714                    }
1715                } break;
1716                case WRITE_SETTINGS: {
1717                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1718                    synchronized (mPackages) {
1719                        removeMessages(WRITE_SETTINGS);
1720                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1721                        mSettings.writeLPr();
1722                        mDirtyUsers.clear();
1723                    }
1724                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1725                } break;
1726                case WRITE_PACKAGE_RESTRICTIONS: {
1727                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1728                    synchronized (mPackages) {
1729                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1730                        for (int userId : mDirtyUsers) {
1731                            mSettings.writePackageRestrictionsLPr(userId);
1732                        }
1733                        mDirtyUsers.clear();
1734                    }
1735                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1736                } break;
1737                case WRITE_PACKAGE_LIST: {
1738                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1739                    synchronized (mPackages) {
1740                        removeMessages(WRITE_PACKAGE_LIST);
1741                        mSettings.writePackageListLPr(msg.arg1);
1742                    }
1743                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1744                } break;
1745                case CHECK_PENDING_VERIFICATION: {
1746                    final int verificationId = msg.arg1;
1747                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1748
1749                    if ((state != null) && !state.timeoutExtended()) {
1750                        final InstallArgs args = state.getInstallArgs();
1751                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1752
1753                        Slog.i(TAG, "Verification timed out for " + originUri);
1754                        mPendingVerification.remove(verificationId);
1755
1756                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1757
1758                        final UserHandle user = args.getUser();
1759                        if (getDefaultVerificationResponse(user)
1760                                == PackageManager.VERIFICATION_ALLOW) {
1761                            Slog.i(TAG, "Continuing with installation of " + originUri);
1762                            state.setVerifierResponse(Binder.getCallingUid(),
1763                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1764                            broadcastPackageVerified(verificationId, originUri,
1765                                    PackageManager.VERIFICATION_ALLOW, user);
1766                            try {
1767                                ret = args.copyApk(mContainerService, true);
1768                            } catch (RemoteException e) {
1769                                Slog.e(TAG, "Could not contact the ContainerService");
1770                            }
1771                        } else {
1772                            broadcastPackageVerified(verificationId, originUri,
1773                                    PackageManager.VERIFICATION_REJECT, user);
1774                        }
1775
1776                        Trace.asyncTraceEnd(
1777                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1778
1779                        processPendingInstall(args, ret);
1780                        mHandler.sendEmptyMessage(MCS_UNBIND);
1781                    }
1782                    break;
1783                }
1784                case PACKAGE_VERIFIED: {
1785                    final int verificationId = msg.arg1;
1786
1787                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1788                    if (state == null) {
1789                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1790                        break;
1791                    }
1792
1793                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1794
1795                    state.setVerifierResponse(response.callerUid, response.code);
1796
1797                    if (state.isVerificationComplete()) {
1798                        mPendingVerification.remove(verificationId);
1799
1800                        final InstallArgs args = state.getInstallArgs();
1801                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1802
1803                        int ret;
1804                        if (state.isInstallAllowed()) {
1805                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1806                            broadcastPackageVerified(verificationId, originUri,
1807                                    response.code, state.getInstallArgs().getUser());
1808                            try {
1809                                ret = args.copyApk(mContainerService, true);
1810                            } catch (RemoteException e) {
1811                                Slog.e(TAG, "Could not contact the ContainerService");
1812                            }
1813                        } else {
1814                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1815                        }
1816
1817                        Trace.asyncTraceEnd(
1818                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1819
1820                        processPendingInstall(args, ret);
1821                        mHandler.sendEmptyMessage(MCS_UNBIND);
1822                    }
1823
1824                    break;
1825                }
1826                case START_INTENT_FILTER_VERIFICATIONS: {
1827                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1828                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1829                            params.replacing, params.pkg);
1830                    break;
1831                }
1832                case INTENT_FILTER_VERIFIED: {
1833                    final int verificationId = msg.arg1;
1834
1835                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1836                            verificationId);
1837                    if (state == null) {
1838                        Slog.w(TAG, "Invalid IntentFilter verification token "
1839                                + verificationId + " received");
1840                        break;
1841                    }
1842
1843                    final int userId = state.getUserId();
1844
1845                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1846                            "Processing IntentFilter verification with token:"
1847                            + verificationId + " and userId:" + userId);
1848
1849                    final IntentFilterVerificationResponse response =
1850                            (IntentFilterVerificationResponse) msg.obj;
1851
1852                    state.setVerifierResponse(response.callerUid, response.code);
1853
1854                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1855                            "IntentFilter verification with token:" + verificationId
1856                            + " and userId:" + userId
1857                            + " is settings verifier response with response code:"
1858                            + response.code);
1859
1860                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1861                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1862                                + response.getFailedDomainsString());
1863                    }
1864
1865                    if (state.isVerificationComplete()) {
1866                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1867                    } else {
1868                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1869                                "IntentFilter verification with token:" + verificationId
1870                                + " was not said to be complete");
1871                    }
1872
1873                    break;
1874                }
1875                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1876                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1877                            mInstantAppResolverConnection,
1878                            (InstantAppRequest) msg.obj,
1879                            mInstantAppInstallerActivity,
1880                            mHandler);
1881                }
1882            }
1883        }
1884    }
1885
1886    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1887            boolean killApp, String[] grantedPermissions,
1888            boolean launchedForRestore, String installerPackage,
1889            IPackageInstallObserver2 installObserver) {
1890        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1891            // Send the removed broadcasts
1892            if (res.removedInfo != null) {
1893                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1894            }
1895
1896            // Now that we successfully installed the package, grant runtime
1897            // permissions if requested before broadcasting the install. Also
1898            // for legacy apps in permission review mode we clear the permission
1899            // review flag which is used to emulate runtime permissions for
1900            // legacy apps.
1901            if (grantPermissions) {
1902                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1903            }
1904
1905            final boolean update = res.removedInfo != null
1906                    && res.removedInfo.removedPackage != null;
1907            final String origInstallerPackageName = res.removedInfo != null
1908                    ? res.removedInfo.installerPackageName : null;
1909
1910            // If this is the first time we have child packages for a disabled privileged
1911            // app that had no children, we grant requested runtime permissions to the new
1912            // children if the parent on the system image had them already granted.
1913            if (res.pkg.parentPackage != null) {
1914                synchronized (mPackages) {
1915                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1916                }
1917            }
1918
1919            synchronized (mPackages) {
1920                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1921            }
1922
1923            final String packageName = res.pkg.applicationInfo.packageName;
1924
1925            // Determine the set of users who are adding this package for
1926            // the first time vs. those who are seeing an update.
1927            int[] firstUsers = EMPTY_INT_ARRAY;
1928            int[] updateUsers = EMPTY_INT_ARRAY;
1929            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1930            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1931            for (int newUser : res.newUsers) {
1932                if (ps.getInstantApp(newUser)) {
1933                    continue;
1934                }
1935                if (allNewUsers) {
1936                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1937                    continue;
1938                }
1939                boolean isNew = true;
1940                for (int origUser : res.origUsers) {
1941                    if (origUser == newUser) {
1942                        isNew = false;
1943                        break;
1944                    }
1945                }
1946                if (isNew) {
1947                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1948                } else {
1949                    updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1950                }
1951            }
1952
1953            // Send installed broadcasts if the package is not a static shared lib.
1954            if (res.pkg.staticSharedLibName == null) {
1955                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1956
1957                // Send added for users that see the package for the first time
1958                // sendPackageAddedForNewUsers also deals with system apps
1959                int appId = UserHandle.getAppId(res.uid);
1960                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1961                sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers);
1962
1963                // Send added for users that don't see the package for the first time
1964                Bundle extras = new Bundle(1);
1965                extras.putInt(Intent.EXTRA_UID, res.uid);
1966                if (update) {
1967                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1968                }
1969                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1970                        extras, 0 /*flags*/,
1971                        null /*targetPackage*/, null /*finishedReceiver*/, updateUsers);
1972                if (origInstallerPackageName != null) {
1973                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1974                            extras, 0 /*flags*/,
1975                            origInstallerPackageName, null /*finishedReceiver*/, updateUsers);
1976                }
1977
1978                // Send replaced for users that don't see the package for the first time
1979                if (update) {
1980                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1981                            packageName, extras, 0 /*flags*/,
1982                            null /*targetPackage*/, null /*finishedReceiver*/,
1983                            updateUsers);
1984                    if (origInstallerPackageName != null) {
1985                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
1986                                extras, 0 /*flags*/,
1987                                origInstallerPackageName, null /*finishedReceiver*/, updateUsers);
1988                    }
1989                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1990                            null /*package*/, null /*extras*/, 0 /*flags*/,
1991                            packageName /*targetPackage*/,
1992                            null /*finishedReceiver*/, updateUsers);
1993                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1994                    // First-install and we did a restore, so we're responsible for the
1995                    // first-launch broadcast.
1996                    if (DEBUG_BACKUP) {
1997                        Slog.i(TAG, "Post-restore of " + packageName
1998                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
1999                    }
2000                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
2001                }
2002
2003                // Send broadcast package appeared if forward locked/external for all users
2004                // treat asec-hosted packages like removable media on upgrade
2005                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2006                    if (DEBUG_INSTALL) {
2007                        Slog.i(TAG, "upgrading pkg " + res.pkg
2008                                + " is ASEC-hosted -> AVAILABLE");
2009                    }
2010                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2011                    ArrayList<String> pkgList = new ArrayList<>(1);
2012                    pkgList.add(packageName);
2013                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2014                }
2015            }
2016
2017            // Work that needs to happen on first install within each user
2018            if (firstUsers != null && firstUsers.length > 0) {
2019                synchronized (mPackages) {
2020                    for (int userId : firstUsers) {
2021                        // If this app is a browser and it's newly-installed for some
2022                        // users, clear any default-browser state in those users. The
2023                        // app's nature doesn't depend on the user, so we can just check
2024                        // its browser nature in any user and generalize.
2025                        if (packageIsBrowser(packageName, userId)) {
2026                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2027                        }
2028
2029                        // We may also need to apply pending (restored) runtime
2030                        // permission grants within these users.
2031                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2032                    }
2033                }
2034            }
2035
2036            // Log current value of "unknown sources" setting
2037            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2038                    getUnknownSourcesSettings());
2039
2040            // Remove the replaced package's older resources safely now
2041            // We delete after a gc for applications  on sdcard.
2042            if (res.removedInfo != null && res.removedInfo.args != null) {
2043                Runtime.getRuntime().gc();
2044                synchronized (mInstallLock) {
2045                    res.removedInfo.args.doPostDeleteLI(true);
2046                }
2047            } else {
2048                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2049                // and not block here.
2050                VMRuntime.getRuntime().requestConcurrentGC();
2051            }
2052
2053            // Notify DexManager that the package was installed for new users.
2054            // The updated users should already be indexed and the package code paths
2055            // should not change.
2056            // Don't notify the manager for ephemeral apps as they are not expected to
2057            // survive long enough to benefit of background optimizations.
2058            for (int userId : firstUsers) {
2059                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2060                // There's a race currently where some install events may interleave with an uninstall.
2061                // This can lead to package info being null (b/36642664).
2062                if (info != null) {
2063                    mDexManager.notifyPackageInstalled(info, userId);
2064                }
2065            }
2066        }
2067
2068        // If someone is watching installs - notify them
2069        if (installObserver != null) {
2070            try {
2071                Bundle extras = extrasForInstallResult(res);
2072                installObserver.onPackageInstalled(res.name, res.returnCode,
2073                        res.returnMsg, extras);
2074            } catch (RemoteException e) {
2075                Slog.i(TAG, "Observer no longer exists.");
2076            }
2077        }
2078    }
2079
2080    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
2081            PackageParser.Package pkg) {
2082        if (pkg.parentPackage == null) {
2083            return;
2084        }
2085        if (pkg.requestedPermissions == null) {
2086            return;
2087        }
2088        final PackageSetting disabledSysParentPs = mSettings
2089                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
2090        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
2091                || !disabledSysParentPs.isPrivileged()
2092                || (disabledSysParentPs.childPackageNames != null
2093                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
2094            return;
2095        }
2096        final int[] allUserIds = sUserManager.getUserIds();
2097        final int permCount = pkg.requestedPermissions.size();
2098        for (int i = 0; i < permCount; i++) {
2099            String permission = pkg.requestedPermissions.get(i);
2100            BasePermission bp = mSettings.mPermissions.get(permission);
2101            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
2102                continue;
2103            }
2104            for (int userId : allUserIds) {
2105                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
2106                        permission, userId)) {
2107                    grantRuntimePermission(pkg.packageName, permission, userId);
2108                }
2109            }
2110        }
2111    }
2112
2113    private StorageEventListener mStorageListener = new StorageEventListener() {
2114        @Override
2115        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2116            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2117                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2118                    final String volumeUuid = vol.getFsUuid();
2119
2120                    // Clean up any users or apps that were removed or recreated
2121                    // while this volume was missing
2122                    sUserManager.reconcileUsers(volumeUuid);
2123                    reconcileApps(volumeUuid);
2124
2125                    // Clean up any install sessions that expired or were
2126                    // cancelled while this volume was missing
2127                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2128
2129                    loadPrivatePackages(vol);
2130
2131                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2132                    unloadPrivatePackages(vol);
2133                }
2134            }
2135
2136            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
2137                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2138                    updateExternalMediaStatus(true, false);
2139                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2140                    updateExternalMediaStatus(false, false);
2141                }
2142            }
2143        }
2144
2145        @Override
2146        public void onVolumeForgotten(String fsUuid) {
2147            if (TextUtils.isEmpty(fsUuid)) {
2148                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2149                return;
2150            }
2151
2152            // Remove any apps installed on the forgotten volume
2153            synchronized (mPackages) {
2154                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2155                for (PackageSetting ps : packages) {
2156                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2157                    deletePackageVersioned(new VersionedPackage(ps.name,
2158                            PackageManager.VERSION_CODE_HIGHEST),
2159                            new LegacyPackageDeleteObserver(null).getBinder(),
2160                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2161                    // Try very hard to release any references to this package
2162                    // so we don't risk the system server being killed due to
2163                    // open FDs
2164                    AttributeCache.instance().removePackage(ps.name);
2165                }
2166
2167                mSettings.onVolumeForgotten(fsUuid);
2168                mSettings.writeLPr();
2169            }
2170        }
2171    };
2172
2173    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2174            String[] grantedPermissions) {
2175        for (int userId : userIds) {
2176            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2177        }
2178    }
2179
2180    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2181            String[] grantedPermissions) {
2182        PackageSetting ps = (PackageSetting) pkg.mExtras;
2183        if (ps == null) {
2184            return;
2185        }
2186
2187        PermissionsState permissionsState = ps.getPermissionsState();
2188
2189        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2190                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2191
2192        final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
2193                >= Build.VERSION_CODES.M;
2194
2195        final boolean instantApp = isInstantApp(pkg.packageName, userId);
2196
2197        for (String permission : pkg.requestedPermissions) {
2198            final BasePermission bp;
2199            synchronized (mPackages) {
2200                bp = mSettings.mPermissions.get(permission);
2201            }
2202            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2203                    && (!instantApp || bp.isInstant())
2204                    && (supportsRuntimePermissions || !bp.isRuntimeOnly())
2205                    && (grantedPermissions == null
2206                           || ArrayUtils.contains(grantedPermissions, permission))) {
2207                final int flags = permissionsState.getPermissionFlags(permission, userId);
2208                if (supportsRuntimePermissions) {
2209                    // Installer cannot change immutable permissions.
2210                    if ((flags & immutableFlags) == 0) {
2211                        grantRuntimePermission(pkg.packageName, permission, userId);
2212                    }
2213                } else if (mPermissionReviewRequired) {
2214                    // In permission review mode we clear the review flag when we
2215                    // are asked to install the app with all permissions granted.
2216                    if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
2217                        updatePermissionFlags(permission, pkg.packageName,
2218                                PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId);
2219                    }
2220                }
2221            }
2222        }
2223    }
2224
2225    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2226        Bundle extras = null;
2227        switch (res.returnCode) {
2228            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2229                extras = new Bundle();
2230                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2231                        res.origPermission);
2232                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2233                        res.origPackage);
2234                break;
2235            }
2236            case PackageManager.INSTALL_SUCCEEDED: {
2237                extras = new Bundle();
2238                extras.putBoolean(Intent.EXTRA_REPLACING,
2239                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2240                break;
2241            }
2242        }
2243        return extras;
2244    }
2245
2246    void scheduleWriteSettingsLocked() {
2247        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2248            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2249        }
2250    }
2251
2252    void scheduleWritePackageListLocked(int userId) {
2253        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2254            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2255            msg.arg1 = userId;
2256            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2257        }
2258    }
2259
2260    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2261        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2262        scheduleWritePackageRestrictionsLocked(userId);
2263    }
2264
2265    void scheduleWritePackageRestrictionsLocked(int userId) {
2266        final int[] userIds = (userId == UserHandle.USER_ALL)
2267                ? sUserManager.getUserIds() : new int[]{userId};
2268        for (int nextUserId : userIds) {
2269            if (!sUserManager.exists(nextUserId)) return;
2270            mDirtyUsers.add(nextUserId);
2271            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2272                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2273            }
2274        }
2275    }
2276
2277    public static PackageManagerService main(Context context, Installer installer,
2278            boolean factoryTest, boolean onlyCore) {
2279        // Self-check for initial settings.
2280        PackageManagerServiceCompilerMapping.checkProperties();
2281
2282        PackageManagerService m = new PackageManagerService(context, installer,
2283                factoryTest, onlyCore);
2284        m.enableSystemUserPackages();
2285        ServiceManager.addService("package", m);
2286        return m;
2287    }
2288
2289    private void enableSystemUserPackages() {
2290        if (!UserManager.isSplitSystemUser()) {
2291            return;
2292        }
2293        // For system user, enable apps based on the following conditions:
2294        // - app is whitelisted or belong to one of these groups:
2295        //   -- system app which has no launcher icons
2296        //   -- system app which has INTERACT_ACROSS_USERS permission
2297        //   -- system IME app
2298        // - app is not in the blacklist
2299        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2300        Set<String> enableApps = new ArraySet<>();
2301        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2302                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2303                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2304        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2305        enableApps.addAll(wlApps);
2306        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2307                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2308        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2309        enableApps.removeAll(blApps);
2310        Log.i(TAG, "Applications installed for system user: " + enableApps);
2311        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2312                UserHandle.SYSTEM);
2313        final int allAppsSize = allAps.size();
2314        synchronized (mPackages) {
2315            for (int i = 0; i < allAppsSize; i++) {
2316                String pName = allAps.get(i);
2317                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2318                // Should not happen, but we shouldn't be failing if it does
2319                if (pkgSetting == null) {
2320                    continue;
2321                }
2322                boolean install = enableApps.contains(pName);
2323                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2324                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2325                            + " for system user");
2326                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2327                }
2328            }
2329            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2330        }
2331    }
2332
2333    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2334        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2335                Context.DISPLAY_SERVICE);
2336        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2337    }
2338
2339    /**
2340     * Requests that files preopted on a secondary system partition be copied to the data partition
2341     * if possible.  Note that the actual copying of the files is accomplished by init for security
2342     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2343     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2344     */
2345    private static void requestCopyPreoptedFiles() {
2346        final int WAIT_TIME_MS = 100;
2347        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2348        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2349            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2350            // We will wait for up to 100 seconds.
2351            final long timeStart = SystemClock.uptimeMillis();
2352            final long timeEnd = timeStart + 100 * 1000;
2353            long timeNow = timeStart;
2354            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2355                try {
2356                    Thread.sleep(WAIT_TIME_MS);
2357                } catch (InterruptedException e) {
2358                    // Do nothing
2359                }
2360                timeNow = SystemClock.uptimeMillis();
2361                if (timeNow > timeEnd) {
2362                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2363                    Slog.wtf(TAG, "cppreopt did not finish!");
2364                    break;
2365                }
2366            }
2367
2368            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2369        }
2370    }
2371
2372    public PackageManagerService(Context context, Installer installer,
2373            boolean factoryTest, boolean onlyCore) {
2374        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2375        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2376        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2377                SystemClock.uptimeMillis());
2378
2379        if (mSdkVersion <= 0) {
2380            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2381        }
2382
2383        mContext = context;
2384
2385        mPermissionReviewRequired = context.getResources().getBoolean(
2386                R.bool.config_permissionReviewRequired);
2387
2388        mFactoryTest = factoryTest;
2389        mOnlyCore = onlyCore;
2390        mMetrics = new DisplayMetrics();
2391        mSettings = new Settings(mPackages);
2392        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2393                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2394        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2395                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2396        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2397                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2398        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2399                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2400        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2401                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2402        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2403                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2404
2405        String separateProcesses = SystemProperties.get("debug.separate_processes");
2406        if (separateProcesses != null && separateProcesses.length() > 0) {
2407            if ("*".equals(separateProcesses)) {
2408                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2409                mSeparateProcesses = null;
2410                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2411            } else {
2412                mDefParseFlags = 0;
2413                mSeparateProcesses = separateProcesses.split(",");
2414                Slog.w(TAG, "Running with debug.separate_processes: "
2415                        + separateProcesses);
2416            }
2417        } else {
2418            mDefParseFlags = 0;
2419            mSeparateProcesses = null;
2420        }
2421
2422        mInstaller = installer;
2423        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2424                "*dexopt*");
2425        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
2426        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2427
2428        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2429                FgThread.get().getLooper());
2430
2431        getDefaultDisplayMetrics(context, mMetrics);
2432
2433        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2434        SystemConfig systemConfig = SystemConfig.getInstance();
2435        mGlobalGids = systemConfig.getGlobalGids();
2436        mSystemPermissions = systemConfig.getSystemPermissions();
2437        mAvailableFeatures = systemConfig.getAvailableFeatures();
2438        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2439
2440        mProtectedPackages = new ProtectedPackages(mContext);
2441
2442        synchronized (mInstallLock) {
2443        // writer
2444        synchronized (mPackages) {
2445            mHandlerThread = new ServiceThread(TAG,
2446                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2447            mHandlerThread.start();
2448            mHandler = new PackageHandler(mHandlerThread.getLooper());
2449            mProcessLoggingHandler = new ProcessLoggingHandler();
2450            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2451
2452            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2453            mInstantAppRegistry = new InstantAppRegistry(this);
2454
2455            File dataDir = Environment.getDataDirectory();
2456            mAppInstallDir = new File(dataDir, "app");
2457            mAppLib32InstallDir = new File(dataDir, "app-lib");
2458            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2459            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2460            sUserManager = new UserManagerService(context, this,
2461                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2462
2463            // Propagate permission configuration in to package manager.
2464            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2465                    = systemConfig.getPermissions();
2466            for (int i=0; i<permConfig.size(); i++) {
2467                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2468                BasePermission bp = mSettings.mPermissions.get(perm.name);
2469                if (bp == null) {
2470                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2471                    mSettings.mPermissions.put(perm.name, bp);
2472                }
2473                if (perm.gids != null) {
2474                    bp.setGids(perm.gids, perm.perUser);
2475                }
2476            }
2477
2478            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2479            final int builtInLibCount = libConfig.size();
2480            for (int i = 0; i < builtInLibCount; i++) {
2481                String name = libConfig.keyAt(i);
2482                String path = libConfig.valueAt(i);
2483                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2484                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2485            }
2486
2487            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2488
2489            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2490            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2491            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2492
2493            // Clean up orphaned packages for which the code path doesn't exist
2494            // and they are an update to a system app - caused by bug/32321269
2495            final int packageSettingCount = mSettings.mPackages.size();
2496            for (int i = packageSettingCount - 1; i >= 0; i--) {
2497                PackageSetting ps = mSettings.mPackages.valueAt(i);
2498                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2499                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2500                    mSettings.mPackages.removeAt(i);
2501                    mSettings.enableSystemPackageLPw(ps.name);
2502                }
2503            }
2504
2505            if (mFirstBoot) {
2506                requestCopyPreoptedFiles();
2507            }
2508
2509            String customResolverActivity = Resources.getSystem().getString(
2510                    R.string.config_customResolverActivity);
2511            if (TextUtils.isEmpty(customResolverActivity)) {
2512                customResolverActivity = null;
2513            } else {
2514                mCustomResolverComponentName = ComponentName.unflattenFromString(
2515                        customResolverActivity);
2516            }
2517
2518            long startTime = SystemClock.uptimeMillis();
2519
2520            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2521                    startTime);
2522
2523            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2524            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2525
2526            if (bootClassPath == null) {
2527                Slog.w(TAG, "No BOOTCLASSPATH found!");
2528            }
2529
2530            if (systemServerClassPath == null) {
2531                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2532            }
2533
2534            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2535
2536            final VersionInfo ver = mSettings.getInternalVersion();
2537            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2538            if (mIsUpgrade) {
2539                logCriticalInfo(Log.INFO,
2540                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2541            }
2542
2543            // when upgrading from pre-M, promote system app permissions from install to runtime
2544            mPromoteSystemApps =
2545                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2546
2547            // When upgrading from pre-N, we need to handle package extraction like first boot,
2548            // as there is no profiling data available.
2549            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2550
2551            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2552
2553            // save off the names of pre-existing system packages prior to scanning; we don't
2554            // want to automatically grant runtime permissions for new system apps
2555            if (mPromoteSystemApps) {
2556                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2557                while (pkgSettingIter.hasNext()) {
2558                    PackageSetting ps = pkgSettingIter.next();
2559                    if (isSystemApp(ps)) {
2560                        mExistingSystemPackages.add(ps.name);
2561                    }
2562                }
2563            }
2564
2565            mCacheDir = preparePackageParserCache(mIsUpgrade);
2566
2567            // Set flag to monitor and not change apk file paths when
2568            // scanning install directories.
2569            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2570
2571            if (mIsUpgrade || mFirstBoot) {
2572                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2573            }
2574
2575            // Collect vendor overlay packages. (Do this before scanning any apps.)
2576            // For security and version matching reason, only consider
2577            // overlay packages if they reside in the right directory.
2578            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2579                    | PackageParser.PARSE_IS_SYSTEM
2580                    | PackageParser.PARSE_IS_SYSTEM_DIR
2581                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2582
2583            mParallelPackageParserCallback.findStaticOverlayPackages();
2584
2585            // Find base frameworks (resource packages without code).
2586            scanDirTracedLI(frameworkDir, mDefParseFlags
2587                    | PackageParser.PARSE_IS_SYSTEM
2588                    | PackageParser.PARSE_IS_SYSTEM_DIR
2589                    | PackageParser.PARSE_IS_PRIVILEGED,
2590                    scanFlags | SCAN_NO_DEX, 0);
2591
2592            // Collected privileged system packages.
2593            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2594            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2595                    | PackageParser.PARSE_IS_SYSTEM
2596                    | PackageParser.PARSE_IS_SYSTEM_DIR
2597                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2598
2599            // Collect ordinary system packages.
2600            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2601            scanDirTracedLI(systemAppDir, mDefParseFlags
2602                    | PackageParser.PARSE_IS_SYSTEM
2603                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2604
2605            // Collect all vendor packages.
2606            File vendorAppDir = new File("/vendor/app");
2607            try {
2608                vendorAppDir = vendorAppDir.getCanonicalFile();
2609            } catch (IOException e) {
2610                // failed to look up canonical path, continue with original one
2611            }
2612            scanDirTracedLI(vendorAppDir, mDefParseFlags
2613                    | PackageParser.PARSE_IS_SYSTEM
2614                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2615
2616            // Collect all OEM packages.
2617            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2618            scanDirTracedLI(oemAppDir, mDefParseFlags
2619                    | PackageParser.PARSE_IS_SYSTEM
2620                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2621
2622            // Prune any system packages that no longer exist.
2623            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2624            if (!mOnlyCore) {
2625                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2626                while (psit.hasNext()) {
2627                    PackageSetting ps = psit.next();
2628
2629                    /*
2630                     * If this is not a system app, it can't be a
2631                     * disable system app.
2632                     */
2633                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2634                        continue;
2635                    }
2636
2637                    /*
2638                     * If the package is scanned, it's not erased.
2639                     */
2640                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2641                    if (scannedPkg != null) {
2642                        /*
2643                         * If the system app is both scanned and in the
2644                         * disabled packages list, then it must have been
2645                         * added via OTA. Remove it from the currently
2646                         * scanned package so the previously user-installed
2647                         * application can be scanned.
2648                         */
2649                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2650                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2651                                    + ps.name + "; removing system app.  Last known codePath="
2652                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2653                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2654                                    + scannedPkg.mVersionCode);
2655                            removePackageLI(scannedPkg, true);
2656                            mExpectingBetter.put(ps.name, ps.codePath);
2657                        }
2658
2659                        continue;
2660                    }
2661
2662                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2663                        psit.remove();
2664                        logCriticalInfo(Log.WARN, "System package " + ps.name
2665                                + " no longer exists; it's data will be wiped");
2666                        // Actual deletion of code and data will be handled by later
2667                        // reconciliation step
2668                    } else {
2669                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2670                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2671                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2672                        }
2673                    }
2674                }
2675            }
2676
2677            //look for any incomplete package installations
2678            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2679            for (int i = 0; i < deletePkgsList.size(); i++) {
2680                // Actual deletion of code and data will be handled by later
2681                // reconciliation step
2682                final String packageName = deletePkgsList.get(i).name;
2683                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2684                synchronized (mPackages) {
2685                    mSettings.removePackageLPw(packageName);
2686                }
2687            }
2688
2689            //delete tmp files
2690            deleteTempPackageFiles();
2691
2692            // Remove any shared userIDs that have no associated packages
2693            mSettings.pruneSharedUsersLPw();
2694
2695            if (!mOnlyCore) {
2696                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2697                        SystemClock.uptimeMillis());
2698                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2699
2700                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2701                        | PackageParser.PARSE_FORWARD_LOCK,
2702                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2703
2704                /**
2705                 * Remove disable package settings for any updated system
2706                 * apps that were removed via an OTA. If they're not a
2707                 * previously-updated app, remove them completely.
2708                 * Otherwise, just revoke their system-level permissions.
2709                 */
2710                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2711                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2712                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2713
2714                    String msg;
2715                    if (deletedPkg == null) {
2716                        msg = "Updated system package " + deletedAppName
2717                                + " no longer exists; it's data will be wiped";
2718                        // Actual deletion of code and data will be handled by later
2719                        // reconciliation step
2720                    } else {
2721                        msg = "Updated system app + " + deletedAppName
2722                                + " no longer present; removing system privileges for "
2723                                + deletedAppName;
2724
2725                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2726
2727                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2728                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2729                    }
2730                    logCriticalInfo(Log.WARN, msg);
2731                }
2732
2733                /**
2734                 * Make sure all system apps that we expected to appear on
2735                 * the userdata partition actually showed up. If they never
2736                 * appeared, crawl back and revive the system version.
2737                 */
2738                for (int i = 0; i < mExpectingBetter.size(); i++) {
2739                    final String packageName = mExpectingBetter.keyAt(i);
2740                    if (!mPackages.containsKey(packageName)) {
2741                        final File scanFile = mExpectingBetter.valueAt(i);
2742
2743                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2744                                + " but never showed up; reverting to system");
2745
2746                        int reparseFlags = mDefParseFlags;
2747                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2748                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2749                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2750                                    | PackageParser.PARSE_IS_PRIVILEGED;
2751                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2752                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2753                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2754                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2755                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2756                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2757                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2758                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2759                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2760                        } else {
2761                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2762                            continue;
2763                        }
2764
2765                        mSettings.enableSystemPackageLPw(packageName);
2766
2767                        try {
2768                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2769                        } catch (PackageManagerException e) {
2770                            Slog.e(TAG, "Failed to parse original system package: "
2771                                    + e.getMessage());
2772                        }
2773                    }
2774                }
2775            }
2776            mExpectingBetter.clear();
2777
2778            // Resolve the storage manager.
2779            mStorageManagerPackage = getStorageManagerPackageName();
2780
2781            // Resolve protected action filters. Only the setup wizard is allowed to
2782            // have a high priority filter for these actions.
2783            mSetupWizardPackage = getSetupWizardPackageName();
2784            if (mProtectedFilters.size() > 0) {
2785                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2786                    Slog.i(TAG, "No setup wizard;"
2787                        + " All protected intents capped to priority 0");
2788                }
2789                for (ActivityIntentInfo filter : mProtectedFilters) {
2790                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2791                        if (DEBUG_FILTERS) {
2792                            Slog.i(TAG, "Found setup wizard;"
2793                                + " allow priority " + filter.getPriority() + ";"
2794                                + " package: " + filter.activity.info.packageName
2795                                + " activity: " + filter.activity.className
2796                                + " priority: " + filter.getPriority());
2797                        }
2798                        // skip setup wizard; allow it to keep the high priority filter
2799                        continue;
2800                    }
2801                    if (DEBUG_FILTERS) {
2802                        Slog.i(TAG, "Protected action; cap priority to 0;"
2803                                + " package: " + filter.activity.info.packageName
2804                                + " activity: " + filter.activity.className
2805                                + " origPrio: " + filter.getPriority());
2806                    }
2807                    filter.setPriority(0);
2808                }
2809            }
2810            mDeferProtectedFilters = false;
2811            mProtectedFilters.clear();
2812
2813            // Now that we know all of the shared libraries, update all clients to have
2814            // the correct library paths.
2815            updateAllSharedLibrariesLPw(null);
2816
2817            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2818                // NOTE: We ignore potential failures here during a system scan (like
2819                // the rest of the commands above) because there's precious little we
2820                // can do about it. A settings error is reported, though.
2821                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2822            }
2823
2824            // Now that we know all the packages we are keeping,
2825            // read and update their last usage times.
2826            mPackageUsage.read(mPackages);
2827            mCompilerStats.read();
2828
2829            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2830                    SystemClock.uptimeMillis());
2831            Slog.i(TAG, "Time to scan packages: "
2832                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2833                    + " seconds");
2834
2835            // If the platform SDK has changed since the last time we booted,
2836            // we need to re-grant app permission to catch any new ones that
2837            // appear.  This is really a hack, and means that apps can in some
2838            // cases get permissions that the user didn't initially explicitly
2839            // allow...  it would be nice to have some better way to handle
2840            // this situation.
2841            int updateFlags = UPDATE_PERMISSIONS_ALL;
2842            if (ver.sdkVersion != mSdkVersion) {
2843                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2844                        + mSdkVersion + "; regranting permissions for internal storage");
2845                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2846            }
2847            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2848            ver.sdkVersion = mSdkVersion;
2849
2850            // If this is the first boot or an update from pre-M, and it is a normal
2851            // boot, then we need to initialize the default preferred apps across
2852            // all defined users.
2853            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2854                for (UserInfo user : sUserManager.getUsers(true)) {
2855                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2856                    applyFactoryDefaultBrowserLPw(user.id);
2857                    primeDomainVerificationsLPw(user.id);
2858                }
2859            }
2860
2861            // Prepare storage for system user really early during boot,
2862            // since core system apps like SettingsProvider and SystemUI
2863            // can't wait for user to start
2864            final int storageFlags;
2865            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2866                storageFlags = StorageManager.FLAG_STORAGE_DE;
2867            } else {
2868                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2869            }
2870            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2871                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2872                    true /* onlyCoreApps */);
2873            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2874                BootTimingsTraceLog traceLog = new BootTimingsTraceLog("SystemServerTimingAsync",
2875                        Trace.TRACE_TAG_PACKAGE_MANAGER);
2876                traceLog.traceBegin("AppDataFixup");
2877                try {
2878                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
2879                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2880                } catch (InstallerException e) {
2881                    Slog.w(TAG, "Trouble fixing GIDs", e);
2882                }
2883                traceLog.traceEnd();
2884
2885                traceLog.traceBegin("AppDataPrepare");
2886                if (deferPackages == null || deferPackages.isEmpty()) {
2887                    return;
2888                }
2889                int count = 0;
2890                for (String pkgName : deferPackages) {
2891                    PackageParser.Package pkg = null;
2892                    synchronized (mPackages) {
2893                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
2894                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
2895                            pkg = ps.pkg;
2896                        }
2897                    }
2898                    if (pkg != null) {
2899                        synchronized (mInstallLock) {
2900                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
2901                                    true /* maybeMigrateAppData */);
2902                        }
2903                        count++;
2904                    }
2905                }
2906                traceLog.traceEnd();
2907                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
2908            }, "prepareAppData");
2909
2910            // If this is first boot after an OTA, and a normal boot, then
2911            // we need to clear code cache directories.
2912            // Note that we do *not* clear the application profiles. These remain valid
2913            // across OTAs and are used to drive profile verification (post OTA) and
2914            // profile compilation (without waiting to collect a fresh set of profiles).
2915            if (mIsUpgrade && !onlyCore) {
2916                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2917                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2918                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2919                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2920                        // No apps are running this early, so no need to freeze
2921                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2922                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2923                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2924                    }
2925                }
2926                ver.fingerprint = Build.FINGERPRINT;
2927            }
2928
2929            checkDefaultBrowser();
2930
2931            // clear only after permissions and other defaults have been updated
2932            mExistingSystemPackages.clear();
2933            mPromoteSystemApps = false;
2934
2935            // All the changes are done during package scanning.
2936            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2937
2938            // can downgrade to reader
2939            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
2940            mSettings.writeLPr();
2941            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2942
2943            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2944                    SystemClock.uptimeMillis());
2945
2946            if (!mOnlyCore) {
2947                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2948                mRequiredInstallerPackage = getRequiredInstallerLPr();
2949                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2950                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2951                if (mIntentFilterVerifierComponent != null) {
2952                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2953                            mIntentFilterVerifierComponent);
2954                } else {
2955                    mIntentFilterVerifier = null;
2956                }
2957                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2958                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
2959                        SharedLibraryInfo.VERSION_UNDEFINED);
2960                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2961                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
2962                        SharedLibraryInfo.VERSION_UNDEFINED);
2963            } else {
2964                mRequiredVerifierPackage = null;
2965                mRequiredInstallerPackage = null;
2966                mRequiredUninstallerPackage = null;
2967                mIntentFilterVerifierComponent = null;
2968                mIntentFilterVerifier = null;
2969                mServicesSystemSharedLibraryPackageName = null;
2970                mSharedSystemSharedLibraryPackageName = null;
2971            }
2972
2973            mInstallerService = new PackageInstallerService(context, this);
2974            final Pair<ComponentName, String> instantAppResolverComponent =
2975                    getInstantAppResolverLPr();
2976            if (instantAppResolverComponent != null) {
2977                if (DEBUG_EPHEMERAL) {
2978                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
2979                }
2980                mInstantAppResolverConnection = new EphemeralResolverConnection(
2981                        mContext, instantAppResolverComponent.first,
2982                        instantAppResolverComponent.second);
2983                mInstantAppResolverSettingsComponent =
2984                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
2985            } else {
2986                mInstantAppResolverConnection = null;
2987                mInstantAppResolverSettingsComponent = null;
2988            }
2989            updateInstantAppInstallerLocked(null);
2990
2991            // Read and update the usage of dex files.
2992            // Do this at the end of PM init so that all the packages have their
2993            // data directory reconciled.
2994            // At this point we know the code paths of the packages, so we can validate
2995            // the disk file and build the internal cache.
2996            // The usage file is expected to be small so loading and verifying it
2997            // should take a fairly small time compare to the other activities (e.g. package
2998            // scanning).
2999            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3000            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3001            for (int userId : currentUserIds) {
3002                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3003            }
3004            mDexManager.load(userPackages);
3005        } // synchronized (mPackages)
3006        } // synchronized (mInstallLock)
3007
3008        // Now after opening every single application zip, make sure they
3009        // are all flushed.  Not really needed, but keeps things nice and
3010        // tidy.
3011        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3012        Runtime.getRuntime().gc();
3013        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3014
3015        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3016        FallbackCategoryProvider.loadFallbacks();
3017        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3018
3019        // The initial scanning above does many calls into installd while
3020        // holding the mPackages lock, but we're mostly interested in yelling
3021        // once we have a booted system.
3022        mInstaller.setWarnIfHeld(mPackages);
3023
3024        // Expose private service for system components to use.
3025        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
3026        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3027    }
3028
3029    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3030        // we're only interested in updating the installer appliction when 1) it's not
3031        // already set or 2) the modified package is the installer
3032        if (mInstantAppInstallerActivity != null
3033                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3034                        .equals(modifiedPackage)) {
3035            return;
3036        }
3037        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3038    }
3039
3040    private static File preparePackageParserCache(boolean isUpgrade) {
3041        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3042            return null;
3043        }
3044
3045        // Disable package parsing on eng builds to allow for faster incremental development.
3046        if ("eng".equals(Build.TYPE)) {
3047            return null;
3048        }
3049
3050        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3051            Slog.i(TAG, "Disabling package parser cache due to system property.");
3052            return null;
3053        }
3054
3055        // The base directory for the package parser cache lives under /data/system/.
3056        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3057                "package_cache");
3058        if (cacheBaseDir == null) {
3059            return null;
3060        }
3061
3062        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3063        // This also serves to "GC" unused entries when the package cache version changes (which
3064        // can only happen during upgrades).
3065        if (isUpgrade) {
3066            FileUtils.deleteContents(cacheBaseDir);
3067        }
3068
3069
3070        // Return the versioned package cache directory. This is something like
3071        // "/data/system/package_cache/1"
3072        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3073
3074        // The following is a workaround to aid development on non-numbered userdebug
3075        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3076        // the system partition is newer.
3077        //
3078        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3079        // that starts with "eng." to signify that this is an engineering build and not
3080        // destined for release.
3081        if ("userdebug".equals(Build.TYPE) && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3082            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3083
3084            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3085            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3086            // in general and should not be used for production changes. In this specific case,
3087            // we know that they will work.
3088            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3089            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3090                FileUtils.deleteContents(cacheBaseDir);
3091                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3092            }
3093        }
3094
3095        return cacheDir;
3096    }
3097
3098    @Override
3099    public boolean isFirstBoot() {
3100        // allow instant applications
3101        return mFirstBoot;
3102    }
3103
3104    @Override
3105    public boolean isOnlyCoreApps() {
3106        // allow instant applications
3107        return mOnlyCore;
3108    }
3109
3110    @Override
3111    public boolean isUpgrade() {
3112        // allow instant applications
3113        return mIsUpgrade;
3114    }
3115
3116    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3117        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3118
3119        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3120                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3121                UserHandle.USER_SYSTEM);
3122        if (matches.size() == 1) {
3123            return matches.get(0).getComponentInfo().packageName;
3124        } else if (matches.size() == 0) {
3125            Log.e(TAG, "There should probably be a verifier, but, none were found");
3126            return null;
3127        }
3128        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3129    }
3130
3131    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3132        synchronized (mPackages) {
3133            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3134            if (libraryEntry == null) {
3135                throw new IllegalStateException("Missing required shared library:" + name);
3136            }
3137            return libraryEntry.apk;
3138        }
3139    }
3140
3141    private @NonNull String getRequiredInstallerLPr() {
3142        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3143        intent.addCategory(Intent.CATEGORY_DEFAULT);
3144        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3145
3146        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3147                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3148                UserHandle.USER_SYSTEM);
3149        if (matches.size() == 1) {
3150            ResolveInfo resolveInfo = matches.get(0);
3151            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3152                throw new RuntimeException("The installer must be a privileged app");
3153            }
3154            return matches.get(0).getComponentInfo().packageName;
3155        } else {
3156            throw new RuntimeException("There must be exactly one installer; found " + matches);
3157        }
3158    }
3159
3160    private @NonNull String getRequiredUninstallerLPr() {
3161        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3162        intent.addCategory(Intent.CATEGORY_DEFAULT);
3163        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3164
3165        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3166                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3167                UserHandle.USER_SYSTEM);
3168        if (resolveInfo == null ||
3169                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3170            throw new RuntimeException("There must be exactly one uninstaller; found "
3171                    + resolveInfo);
3172        }
3173        return resolveInfo.getComponentInfo().packageName;
3174    }
3175
3176    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3177        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3178
3179        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3180                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3181                UserHandle.USER_SYSTEM);
3182        ResolveInfo best = null;
3183        final int N = matches.size();
3184        for (int i = 0; i < N; i++) {
3185            final ResolveInfo cur = matches.get(i);
3186            final String packageName = cur.getComponentInfo().packageName;
3187            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3188                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3189                continue;
3190            }
3191
3192            if (best == null || cur.priority > best.priority) {
3193                best = cur;
3194            }
3195        }
3196
3197        if (best != null) {
3198            return best.getComponentInfo().getComponentName();
3199        }
3200        Slog.w(TAG, "Intent filter verifier not found");
3201        return null;
3202    }
3203
3204    @Override
3205    public @Nullable ComponentName getInstantAppResolverComponent() {
3206        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3207            return null;
3208        }
3209        synchronized (mPackages) {
3210            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3211            if (instantAppResolver == null) {
3212                return null;
3213            }
3214            return instantAppResolver.first;
3215        }
3216    }
3217
3218    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3219        final String[] packageArray =
3220                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3221        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3222            if (DEBUG_EPHEMERAL) {
3223                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3224            }
3225            return null;
3226        }
3227
3228        final int callingUid = Binder.getCallingUid();
3229        final int resolveFlags =
3230                MATCH_DIRECT_BOOT_AWARE
3231                | MATCH_DIRECT_BOOT_UNAWARE
3232                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3233        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3234        final Intent resolverIntent = new Intent(actionName);
3235        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3236                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3237        // temporarily look for the old action
3238        if (resolvers.size() == 0) {
3239            if (DEBUG_EPHEMERAL) {
3240                Slog.d(TAG, "Ephemeral resolver not found with new action; try old one");
3241            }
3242            actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE;
3243            resolverIntent.setAction(actionName);
3244            resolvers = queryIntentServicesInternal(resolverIntent, null,
3245                    resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3246        }
3247        final int N = resolvers.size();
3248        if (N == 0) {
3249            if (DEBUG_EPHEMERAL) {
3250                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3251            }
3252            return null;
3253        }
3254
3255        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3256        for (int i = 0; i < N; i++) {
3257            final ResolveInfo info = resolvers.get(i);
3258
3259            if (info.serviceInfo == null) {
3260                continue;
3261            }
3262
3263            final String packageName = info.serviceInfo.packageName;
3264            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3265                if (DEBUG_EPHEMERAL) {
3266                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3267                            + " pkg: " + packageName + ", info:" + info);
3268                }
3269                continue;
3270            }
3271
3272            if (DEBUG_EPHEMERAL) {
3273                Slog.v(TAG, "Ephemeral resolver found;"
3274                        + " pkg: " + packageName + ", info:" + info);
3275            }
3276            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3277        }
3278        if (DEBUG_EPHEMERAL) {
3279            Slog.v(TAG, "Ephemeral resolver NOT found");
3280        }
3281        return null;
3282    }
3283
3284    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3285        final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE);
3286        intent.addCategory(Intent.CATEGORY_DEFAULT);
3287        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3288
3289        final int resolveFlags =
3290                MATCH_DIRECT_BOOT_AWARE
3291                | MATCH_DIRECT_BOOT_UNAWARE
3292                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3293        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3294                resolveFlags, UserHandle.USER_SYSTEM);
3295        // temporarily look for the old action
3296        if (matches.isEmpty()) {
3297            if (DEBUG_EPHEMERAL) {
3298                Slog.d(TAG, "Ephemeral installer not found with new action; try old one");
3299            }
3300            intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3301            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3302                    resolveFlags, UserHandle.USER_SYSTEM);
3303        }
3304        Iterator<ResolveInfo> iter = matches.iterator();
3305        while (iter.hasNext()) {
3306            final ResolveInfo rInfo = iter.next();
3307            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3308            if (ps != null) {
3309                final PermissionsState permissionsState = ps.getPermissionsState();
3310                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3311                    continue;
3312                }
3313            }
3314            iter.remove();
3315        }
3316        if (matches.size() == 0) {
3317            return null;
3318        } else if (matches.size() == 1) {
3319            return (ActivityInfo) matches.get(0).getComponentInfo();
3320        } else {
3321            throw new RuntimeException(
3322                    "There must be at most one ephemeral installer; found " + matches);
3323        }
3324    }
3325
3326    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3327            @NonNull ComponentName resolver) {
3328        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3329                .addCategory(Intent.CATEGORY_DEFAULT)
3330                .setPackage(resolver.getPackageName());
3331        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3332        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3333                UserHandle.USER_SYSTEM);
3334        // temporarily look for the old action
3335        if (matches.isEmpty()) {
3336            if (DEBUG_EPHEMERAL) {
3337                Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one");
3338            }
3339            intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS);
3340            matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3341                    UserHandle.USER_SYSTEM);
3342        }
3343        if (matches.isEmpty()) {
3344            return null;
3345        }
3346        return matches.get(0).getComponentInfo().getComponentName();
3347    }
3348
3349    private void primeDomainVerificationsLPw(int userId) {
3350        if (DEBUG_DOMAIN_VERIFICATION) {
3351            Slog.d(TAG, "Priming domain verifications in user " + userId);
3352        }
3353
3354        SystemConfig systemConfig = SystemConfig.getInstance();
3355        ArraySet<String> packages = systemConfig.getLinkedApps();
3356
3357        for (String packageName : packages) {
3358            PackageParser.Package pkg = mPackages.get(packageName);
3359            if (pkg != null) {
3360                if (!pkg.isSystemApp()) {
3361                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3362                    continue;
3363                }
3364
3365                ArraySet<String> domains = null;
3366                for (PackageParser.Activity a : pkg.activities) {
3367                    for (ActivityIntentInfo filter : a.intents) {
3368                        if (hasValidDomains(filter)) {
3369                            if (domains == null) {
3370                                domains = new ArraySet<String>();
3371                            }
3372                            domains.addAll(filter.getHostsList());
3373                        }
3374                    }
3375                }
3376
3377                if (domains != null && domains.size() > 0) {
3378                    if (DEBUG_DOMAIN_VERIFICATION) {
3379                        Slog.v(TAG, "      + " + packageName);
3380                    }
3381                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3382                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3383                    // and then 'always' in the per-user state actually used for intent resolution.
3384                    final IntentFilterVerificationInfo ivi;
3385                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3386                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3387                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3388                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3389                } else {
3390                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3391                            + "' does not handle web links");
3392                }
3393            } else {
3394                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3395            }
3396        }
3397
3398        scheduleWritePackageRestrictionsLocked(userId);
3399        scheduleWriteSettingsLocked();
3400    }
3401
3402    private void applyFactoryDefaultBrowserLPw(int userId) {
3403        // The default browser app's package name is stored in a string resource,
3404        // with a product-specific overlay used for vendor customization.
3405        String browserPkg = mContext.getResources().getString(
3406                com.android.internal.R.string.default_browser);
3407        if (!TextUtils.isEmpty(browserPkg)) {
3408            // non-empty string => required to be a known package
3409            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3410            if (ps == null) {
3411                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3412                browserPkg = null;
3413            } else {
3414                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3415            }
3416        }
3417
3418        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3419        // default.  If there's more than one, just leave everything alone.
3420        if (browserPkg == null) {
3421            calculateDefaultBrowserLPw(userId);
3422        }
3423    }
3424
3425    private void calculateDefaultBrowserLPw(int userId) {
3426        List<String> allBrowsers = resolveAllBrowserApps(userId);
3427        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3428        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3429    }
3430
3431    private List<String> resolveAllBrowserApps(int userId) {
3432        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3433        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3434                PackageManager.MATCH_ALL, userId);
3435
3436        final int count = list.size();
3437        List<String> result = new ArrayList<String>(count);
3438        for (int i=0; i<count; i++) {
3439            ResolveInfo info = list.get(i);
3440            if (info.activityInfo == null
3441                    || !info.handleAllWebDataURI
3442                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3443                    || result.contains(info.activityInfo.packageName)) {
3444                continue;
3445            }
3446            result.add(info.activityInfo.packageName);
3447        }
3448
3449        return result;
3450    }
3451
3452    private boolean packageIsBrowser(String packageName, int userId) {
3453        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3454                PackageManager.MATCH_ALL, userId);
3455        final int N = list.size();
3456        for (int i = 0; i < N; i++) {
3457            ResolveInfo info = list.get(i);
3458            if (packageName.equals(info.activityInfo.packageName)) {
3459                return true;
3460            }
3461        }
3462        return false;
3463    }
3464
3465    private void checkDefaultBrowser() {
3466        final int myUserId = UserHandle.myUserId();
3467        final String packageName = getDefaultBrowserPackageName(myUserId);
3468        if (packageName != null) {
3469            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3470            if (info == null) {
3471                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3472                synchronized (mPackages) {
3473                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3474                }
3475            }
3476        }
3477    }
3478
3479    @Override
3480    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3481            throws RemoteException {
3482        try {
3483            return super.onTransact(code, data, reply, flags);
3484        } catch (RuntimeException e) {
3485            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3486                Slog.wtf(TAG, "Package Manager Crash", e);
3487            }
3488            throw e;
3489        }
3490    }
3491
3492    static int[] appendInts(int[] cur, int[] add) {
3493        if (add == null) return cur;
3494        if (cur == null) return add;
3495        final int N = add.length;
3496        for (int i=0; i<N; i++) {
3497            cur = appendInt(cur, add[i]);
3498        }
3499        return cur;
3500    }
3501
3502    /**
3503     * Returns whether or not a full application can see an instant application.
3504     * <p>
3505     * Currently, there are three cases in which this can occur:
3506     * <ol>
3507     * <li>The calling application is a "special" process. The special
3508     *     processes are {@link Process#SYSTEM_UID}, {@link Process#SHELL_UID}
3509     *     and {@code 0}</li>
3510     * <li>The calling application has the permission
3511     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}</li>
3512     * <li>The calling application is the default launcher on the
3513     *     system partition.</li>
3514     * </ol>
3515     */
3516    private boolean canViewInstantApps(int callingUid, int userId) {
3517        if (callingUid == Process.SYSTEM_UID
3518                || callingUid == Process.SHELL_UID
3519                || callingUid == Process.ROOT_UID) {
3520            return true;
3521        }
3522        if (mContext.checkCallingOrSelfPermission(
3523                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3524            return true;
3525        }
3526        if (mContext.checkCallingOrSelfPermission(
3527                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3528            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3529            if (homeComponent != null
3530                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3531                return true;
3532            }
3533        }
3534        return false;
3535    }
3536
3537    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3538        if (!sUserManager.exists(userId)) return null;
3539        if (ps == null) {
3540            return null;
3541        }
3542        PackageParser.Package p = ps.pkg;
3543        if (p == null) {
3544            return null;
3545        }
3546        final int callingUid = Binder.getCallingUid();
3547        // Filter out ephemeral app metadata:
3548        //   * The system/shell/root can see metadata for any app
3549        //   * An installed app can see metadata for 1) other installed apps
3550        //     and 2) ephemeral apps that have explicitly interacted with it
3551        //   * Ephemeral apps can only see their own data and exposed installed apps
3552        //   * Holding a signature permission allows seeing instant apps
3553        if (filterAppAccessLPr(ps, callingUid, userId)) {
3554            return null;
3555        }
3556
3557        final PermissionsState permissionsState = ps.getPermissionsState();
3558
3559        // Compute GIDs only if requested
3560        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3561                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3562        // Compute granted permissions only if package has requested permissions
3563        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3564                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3565        final PackageUserState state = ps.readUserState(userId);
3566
3567        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3568                && ps.isSystem()) {
3569            flags |= MATCH_ANY_USER;
3570        }
3571
3572        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3573                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3574
3575        if (packageInfo == null) {
3576            return null;
3577        }
3578
3579        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3580                resolveExternalPackageNameLPr(p);
3581
3582        return packageInfo;
3583    }
3584
3585    @Override
3586    public void checkPackageStartable(String packageName, int userId) {
3587        final int callingUid = Binder.getCallingUid();
3588        if (getInstantAppPackageName(callingUid) != null) {
3589            throw new SecurityException("Instant applications don't have access to this method");
3590        }
3591        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3592        synchronized (mPackages) {
3593            final PackageSetting ps = mSettings.mPackages.get(packageName);
3594            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3595                throw new SecurityException("Package " + packageName + " was not found!");
3596            }
3597
3598            if (!ps.getInstalled(userId)) {
3599                throw new SecurityException(
3600                        "Package " + packageName + " was not installed for user " + userId + "!");
3601            }
3602
3603            if (mSafeMode && !ps.isSystem()) {
3604                throw new SecurityException("Package " + packageName + " not a system app!");
3605            }
3606
3607            if (mFrozenPackages.contains(packageName)) {
3608                throw new SecurityException("Package " + packageName + " is currently frozen!");
3609            }
3610
3611            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3612                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3613                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3614            }
3615        }
3616    }
3617
3618    @Override
3619    public boolean isPackageAvailable(String packageName, int userId) {
3620        if (!sUserManager.exists(userId)) return false;
3621        final int callingUid = Binder.getCallingUid();
3622        enforceCrossUserPermission(callingUid, userId,
3623                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
3624        synchronized (mPackages) {
3625            PackageParser.Package p = mPackages.get(packageName);
3626            if (p != null) {
3627                final PackageSetting ps = (PackageSetting) p.mExtras;
3628                if (filterAppAccessLPr(ps, callingUid, userId)) {
3629                    return false;
3630                }
3631                if (ps != null) {
3632                    final PackageUserState state = ps.readUserState(userId);
3633                    if (state != null) {
3634                        return PackageParser.isAvailable(state);
3635                    }
3636                }
3637            }
3638        }
3639        return false;
3640    }
3641
3642    @Override
3643    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3644        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3645                flags, Binder.getCallingUid(), userId);
3646    }
3647
3648    @Override
3649    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3650            int flags, int userId) {
3651        return getPackageInfoInternal(versionedPackage.getPackageName(),
3652                versionedPackage.getVersionCode(), flags, Binder.getCallingUid(), userId);
3653    }
3654
3655    /**
3656     * Important: The provided filterCallingUid is used exclusively to filter out packages
3657     * that can be seen based on user state. It's typically the original caller uid prior
3658     * to clearing. Because it can only be provided by trusted code, it's value can be
3659     * trusted and will be used as-is; unlike userId which will be validated by this method.
3660     */
3661    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3662            int flags, int filterCallingUid, int userId) {
3663        if (!sUserManager.exists(userId)) return null;
3664        flags = updateFlagsForPackage(flags, userId, packageName);
3665        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3666                false /* requireFullPermission */, false /* checkShell */, "get package info");
3667
3668        // reader
3669        synchronized (mPackages) {
3670            // Normalize package name to handle renamed packages and static libs
3671            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3672
3673            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3674            if (matchFactoryOnly) {
3675                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3676                if (ps != null) {
3677                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3678                        return null;
3679                    }
3680                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3681                        return null;
3682                    }
3683                    return generatePackageInfo(ps, flags, userId);
3684                }
3685            }
3686
3687            PackageParser.Package p = mPackages.get(packageName);
3688            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3689                return null;
3690            }
3691            if (DEBUG_PACKAGE_INFO)
3692                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3693            if (p != null) {
3694                final PackageSetting ps = (PackageSetting) p.mExtras;
3695                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3696                    return null;
3697                }
3698                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
3699                    return null;
3700                }
3701                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3702            }
3703            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3704                final PackageSetting ps = mSettings.mPackages.get(packageName);
3705                if (ps == null) return null;
3706                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3707                    return null;
3708                }
3709                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3710                    return null;
3711                }
3712                return generatePackageInfo(ps, flags, userId);
3713            }
3714        }
3715        return null;
3716    }
3717
3718    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
3719        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
3720            return true;
3721        }
3722        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
3723            return true;
3724        }
3725        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
3726            return true;
3727        }
3728        return false;
3729    }
3730
3731    private boolean isComponentVisibleToInstantApp(
3732            @Nullable ComponentName component, @ComponentType int type) {
3733        if (type == TYPE_ACTIVITY) {
3734            final PackageParser.Activity activity = mActivities.mActivities.get(component);
3735            return activity != null
3736                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3737                    : false;
3738        } else if (type == TYPE_RECEIVER) {
3739            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
3740            return activity != null
3741                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3742                    : false;
3743        } else if (type == TYPE_SERVICE) {
3744            final PackageParser.Service service = mServices.mServices.get(component);
3745            return service != null
3746                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3747                    : false;
3748        } else if (type == TYPE_PROVIDER) {
3749            final PackageParser.Provider provider = mProviders.mProviders.get(component);
3750            return provider != null
3751                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3752                    : false;
3753        } else if (type == TYPE_UNKNOWN) {
3754            return isComponentVisibleToInstantApp(component);
3755        }
3756        return false;
3757    }
3758
3759    /**
3760     * Returns whether or not access to the application should be filtered.
3761     * <p>
3762     * Access may be limited based upon whether the calling or target applications
3763     * are instant applications.
3764     *
3765     * @see #canAccessInstantApps(int)
3766     */
3767    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
3768            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
3769        // if we're in an isolated process, get the real calling UID
3770        if (Process.isIsolated(callingUid)) {
3771            callingUid = mIsolatedOwners.get(callingUid);
3772        }
3773        final String instantAppPkgName = getInstantAppPackageName(callingUid);
3774        final boolean callerIsInstantApp = instantAppPkgName != null;
3775        if (ps == null) {
3776            if (callerIsInstantApp) {
3777                // pretend the application exists, but, needs to be filtered
3778                return true;
3779            }
3780            return false;
3781        }
3782        // if the target and caller are the same application, don't filter
3783        if (isCallerSameApp(ps.name, callingUid)) {
3784            return false;
3785        }
3786        if (callerIsInstantApp) {
3787            // request for a specific component; if it hasn't been explicitly exposed, filter
3788            if (component != null) {
3789                return !isComponentVisibleToInstantApp(component, componentType);
3790            }
3791            // request for application; if no components have been explicitly exposed, filter
3792            return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps;
3793        }
3794        if (ps.getInstantApp(userId)) {
3795            // caller can see all components of all instant applications, don't filter
3796            if (canViewInstantApps(callingUid, userId)) {
3797                return false;
3798            }
3799            // request for a specific instant application component, filter
3800            if (component != null) {
3801                return true;
3802            }
3803            // request for an instant application; if the caller hasn't been granted access, filter
3804            return !mInstantAppRegistry.isInstantAccessGranted(
3805                    userId, UserHandle.getAppId(callingUid), ps.appId);
3806        }
3807        return false;
3808    }
3809
3810    /**
3811     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
3812     */
3813    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
3814        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
3815    }
3816
3817    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
3818            int flags) {
3819        // Callers can access only the libs they depend on, otherwise they need to explicitly
3820        // ask for the shared libraries given the caller is allowed to access all static libs.
3821        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
3822            // System/shell/root get to see all static libs
3823            final int appId = UserHandle.getAppId(uid);
3824            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
3825                    || appId == Process.ROOT_UID) {
3826                return false;
3827            }
3828        }
3829
3830        // No package means no static lib as it is always on internal storage
3831        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
3832            return false;
3833        }
3834
3835        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
3836                ps.pkg.staticSharedLibVersion);
3837        if (libEntry == null) {
3838            return false;
3839        }
3840
3841        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
3842        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
3843        if (uidPackageNames == null) {
3844            return true;
3845        }
3846
3847        for (String uidPackageName : uidPackageNames) {
3848            if (ps.name.equals(uidPackageName)) {
3849                return false;
3850            }
3851            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
3852            if (uidPs != null) {
3853                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
3854                        libEntry.info.getName());
3855                if (index < 0) {
3856                    continue;
3857                }
3858                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
3859                    return false;
3860                }
3861            }
3862        }
3863        return true;
3864    }
3865
3866    @Override
3867    public String[] currentToCanonicalPackageNames(String[] names) {
3868        final int callingUid = Binder.getCallingUid();
3869        if (getInstantAppPackageName(callingUid) != null) {
3870            return names;
3871        }
3872        final String[] out = new String[names.length];
3873        // reader
3874        synchronized (mPackages) {
3875            final int callingUserId = UserHandle.getUserId(callingUid);
3876            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
3877            for (int i=names.length-1; i>=0; i--) {
3878                final PackageSetting ps = mSettings.mPackages.get(names[i]);
3879                boolean translateName = false;
3880                if (ps != null && ps.realName != null) {
3881                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
3882                    translateName = !targetIsInstantApp
3883                            || canViewInstantApps
3884                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
3885                                    UserHandle.getAppId(callingUid), ps.appId);
3886                }
3887                out[i] = translateName ? ps.realName : names[i];
3888            }
3889        }
3890        return out;
3891    }
3892
3893    @Override
3894    public String[] canonicalToCurrentPackageNames(String[] names) {
3895        final int callingUid = Binder.getCallingUid();
3896        if (getInstantAppPackageName(callingUid) != null) {
3897            return names;
3898        }
3899        final String[] out = new String[names.length];
3900        // reader
3901        synchronized (mPackages) {
3902            final int callingUserId = UserHandle.getUserId(callingUid);
3903            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
3904            for (int i=names.length-1; i>=0; i--) {
3905                final String cur = mSettings.getRenamedPackageLPr(names[i]);
3906                boolean translateName = false;
3907                if (cur != null) {
3908                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
3909                    final boolean targetIsInstantApp =
3910                            ps != null && ps.getInstantApp(callingUserId);
3911                    translateName = !targetIsInstantApp
3912                            || canViewInstantApps
3913                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
3914                                    UserHandle.getAppId(callingUid), ps.appId);
3915                }
3916                out[i] = translateName ? cur : names[i];
3917            }
3918        }
3919        return out;
3920    }
3921
3922    @Override
3923    public int getPackageUid(String packageName, int flags, int userId) {
3924        if (!sUserManager.exists(userId)) return -1;
3925        final int callingUid = Binder.getCallingUid();
3926        flags = updateFlagsForPackage(flags, userId, packageName);
3927        enforceCrossUserPermission(callingUid, userId,
3928                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
3929
3930        // reader
3931        synchronized (mPackages) {
3932            final PackageParser.Package p = mPackages.get(packageName);
3933            if (p != null && p.isMatch(flags)) {
3934                PackageSetting ps = (PackageSetting) p.mExtras;
3935                if (filterAppAccessLPr(ps, callingUid, userId)) {
3936                    return -1;
3937                }
3938                return UserHandle.getUid(userId, p.applicationInfo.uid);
3939            }
3940            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3941                final PackageSetting ps = mSettings.mPackages.get(packageName);
3942                if (ps != null && ps.isMatch(flags)
3943                        && !filterAppAccessLPr(ps, callingUid, userId)) {
3944                    return UserHandle.getUid(userId, ps.appId);
3945                }
3946            }
3947        }
3948
3949        return -1;
3950    }
3951
3952    @Override
3953    public int[] getPackageGids(String packageName, int flags, int userId) {
3954        if (!sUserManager.exists(userId)) return null;
3955        final int callingUid = Binder.getCallingUid();
3956        flags = updateFlagsForPackage(flags, userId, packageName);
3957        enforceCrossUserPermission(callingUid, userId,
3958                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
3959
3960        // reader
3961        synchronized (mPackages) {
3962            final PackageParser.Package p = mPackages.get(packageName);
3963            if (p != null && p.isMatch(flags)) {
3964                PackageSetting ps = (PackageSetting) p.mExtras;
3965                if (filterAppAccessLPr(ps, callingUid, userId)) {
3966                    return null;
3967                }
3968                // TODO: Shouldn't this be checking for package installed state for userId and
3969                // return null?
3970                return ps.getPermissionsState().computeGids(userId);
3971            }
3972            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3973                final PackageSetting ps = mSettings.mPackages.get(packageName);
3974                if (ps != null && ps.isMatch(flags)
3975                        && !filterAppAccessLPr(ps, callingUid, userId)) {
3976                    return ps.getPermissionsState().computeGids(userId);
3977                }
3978            }
3979        }
3980
3981        return null;
3982    }
3983
3984    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3985        if (bp.perm != null) {
3986            return PackageParser.generatePermissionInfo(bp.perm, flags);
3987        }
3988        PermissionInfo pi = new PermissionInfo();
3989        pi.name = bp.name;
3990        pi.packageName = bp.sourcePackage;
3991        pi.nonLocalizedLabel = bp.name;
3992        pi.protectionLevel = bp.protectionLevel;
3993        return pi;
3994    }
3995
3996    @Override
3997    public PermissionInfo getPermissionInfo(String name, int flags) {
3998        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3999            return null;
4000        }
4001        // reader
4002        synchronized (mPackages) {
4003            final BasePermission p = mSettings.mPermissions.get(name);
4004            if (p != null) {
4005                return generatePermissionInfo(p, flags);
4006            }
4007            return null;
4008        }
4009    }
4010
4011    @Override
4012    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
4013            int flags) {
4014        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4015            return null;
4016        }
4017        // reader
4018        synchronized (mPackages) {
4019            if (group != null && !mPermissionGroups.containsKey(group)) {
4020                // This is thrown as NameNotFoundException
4021                return null;
4022            }
4023
4024            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
4025            for (BasePermission p : mSettings.mPermissions.values()) {
4026                if (group == null) {
4027                    if (p.perm == null || p.perm.info.group == null) {
4028                        out.add(generatePermissionInfo(p, flags));
4029                    }
4030                } else {
4031                    if (p.perm != null && group.equals(p.perm.info.group)) {
4032                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
4033                    }
4034                }
4035            }
4036            return new ParceledListSlice<>(out);
4037        }
4038    }
4039
4040    @Override
4041    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
4042        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4043            return null;
4044        }
4045        // reader
4046        synchronized (mPackages) {
4047            return PackageParser.generatePermissionGroupInfo(
4048                    mPermissionGroups.get(name), flags);
4049        }
4050    }
4051
4052    @Override
4053    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4054        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4055            return ParceledListSlice.emptyList();
4056        }
4057        // reader
4058        synchronized (mPackages) {
4059            final int N = mPermissionGroups.size();
4060            ArrayList<PermissionGroupInfo> out
4061                    = new ArrayList<PermissionGroupInfo>(N);
4062            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
4063                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
4064            }
4065            return new ParceledListSlice<>(out);
4066        }
4067    }
4068
4069    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4070            int filterCallingUid, int userId) {
4071        if (!sUserManager.exists(userId)) return null;
4072        PackageSetting ps = mSettings.mPackages.get(packageName);
4073        if (ps != null) {
4074            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4075                return null;
4076            }
4077            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4078                return null;
4079            }
4080            if (ps.pkg == null) {
4081                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4082                if (pInfo != null) {
4083                    return pInfo.applicationInfo;
4084                }
4085                return null;
4086            }
4087            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4088                    ps.readUserState(userId), userId);
4089            if (ai != null) {
4090                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4091            }
4092            return ai;
4093        }
4094        return null;
4095    }
4096
4097    @Override
4098    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4099        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4100    }
4101
4102    /**
4103     * Important: The provided filterCallingUid is used exclusively to filter out applications
4104     * that can be seen based on user state. It's typically the original caller uid prior
4105     * to clearing. Because it can only be provided by trusted code, it's value can be
4106     * trusted and will be used as-is; unlike userId which will be validated by this method.
4107     */
4108    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4109            int filterCallingUid, int userId) {
4110        if (!sUserManager.exists(userId)) return null;
4111        flags = updateFlagsForApplication(flags, userId, packageName);
4112        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4113                false /* requireFullPermission */, false /* checkShell */, "get application info");
4114
4115        // writer
4116        synchronized (mPackages) {
4117            // Normalize package name to handle renamed packages and static libs
4118            packageName = resolveInternalPackageNameLPr(packageName,
4119                    PackageManager.VERSION_CODE_HIGHEST);
4120
4121            PackageParser.Package p = mPackages.get(packageName);
4122            if (DEBUG_PACKAGE_INFO) Log.v(
4123                    TAG, "getApplicationInfo " + packageName
4124                    + ": " + p);
4125            if (p != null) {
4126                PackageSetting ps = mSettings.mPackages.get(packageName);
4127                if (ps == null) return null;
4128                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4129                    return null;
4130                }
4131                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4132                    return null;
4133                }
4134                // Note: isEnabledLP() does not apply here - always return info
4135                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4136                        p, flags, ps.readUserState(userId), userId);
4137                if (ai != null) {
4138                    ai.packageName = resolveExternalPackageNameLPr(p);
4139                }
4140                return ai;
4141            }
4142            if ("android".equals(packageName)||"system".equals(packageName)) {
4143                return mAndroidApplication;
4144            }
4145            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4146                // Already generates the external package name
4147                return generateApplicationInfoFromSettingsLPw(packageName,
4148                        flags, filterCallingUid, userId);
4149            }
4150        }
4151        return null;
4152    }
4153
4154    private String normalizePackageNameLPr(String packageName) {
4155        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4156        return normalizedPackageName != null ? normalizedPackageName : packageName;
4157    }
4158
4159    @Override
4160    public void deletePreloadsFileCache() {
4161        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4162            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4163        }
4164        File dir = Environment.getDataPreloadsFileCacheDirectory();
4165        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4166        FileUtils.deleteContents(dir);
4167    }
4168
4169    @Override
4170    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4171            final int storageFlags, final IPackageDataObserver observer) {
4172        mContext.enforceCallingOrSelfPermission(
4173                android.Manifest.permission.CLEAR_APP_CACHE, null);
4174        mHandler.post(() -> {
4175            boolean success = false;
4176            try {
4177                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4178                success = true;
4179            } catch (IOException e) {
4180                Slog.w(TAG, e);
4181            }
4182            if (observer != null) {
4183                try {
4184                    observer.onRemoveCompleted(null, success);
4185                } catch (RemoteException e) {
4186                    Slog.w(TAG, e);
4187                }
4188            }
4189        });
4190    }
4191
4192    @Override
4193    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4194            final int storageFlags, final IntentSender pi) {
4195        mContext.enforceCallingOrSelfPermission(
4196                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4197        mHandler.post(() -> {
4198            boolean success = false;
4199            try {
4200                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4201                success = true;
4202            } catch (IOException e) {
4203                Slog.w(TAG, e);
4204            }
4205            if (pi != null) {
4206                try {
4207                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4208                } catch (SendIntentException e) {
4209                    Slog.w(TAG, e);
4210                }
4211            }
4212        });
4213    }
4214
4215    /**
4216     * Blocking call to clear various types of cached data across the system
4217     * until the requested bytes are available.
4218     */
4219    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4220        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4221        final File file = storage.findPathForUuid(volumeUuid);
4222        if (file.getUsableSpace() >= bytes) return;
4223
4224        if (ENABLE_FREE_CACHE_V2) {
4225            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4226                    volumeUuid);
4227            final boolean aggressive = (storageFlags
4228                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4229            final boolean defyReserved = (storageFlags
4230                    & StorageManager.FLAG_ALLOCATE_DEFY_RESERVED) != 0;
4231            final long reservedBytes = (aggressive || defyReserved) ? 0
4232                    : storage.getStorageCacheBytes(file);
4233
4234            // 1. Pre-flight to determine if we have any chance to succeed
4235            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4236            if (internalVolume && (aggressive || SystemProperties
4237                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4238                deletePreloadsFileCache();
4239                if (file.getUsableSpace() >= bytes) return;
4240            }
4241
4242            // 3. Consider parsed APK data (aggressive only)
4243            if (internalVolume && aggressive) {
4244                FileUtils.deleteContents(mCacheDir);
4245                if (file.getUsableSpace() >= bytes) return;
4246            }
4247
4248            // 4. Consider cached app data (above quotas)
4249            try {
4250                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4251                        Installer.FLAG_FREE_CACHE_V2);
4252            } catch (InstallerException ignored) {
4253            }
4254            if (file.getUsableSpace() >= bytes) return;
4255
4256            // 5. Consider shared libraries with refcount=0 and age>min cache period
4257            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4258                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4259                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4260                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4261                return;
4262            }
4263
4264            // 6. Consider dexopt output (aggressive only)
4265            // TODO: Implement
4266
4267            // 7. Consider installed instant apps unused longer than min cache period
4268            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4269                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4270                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4271                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4272                return;
4273            }
4274
4275            // 8. Consider cached app data (below quotas)
4276            try {
4277                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4278                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4279            } catch (InstallerException ignored) {
4280            }
4281            if (file.getUsableSpace() >= bytes) return;
4282
4283            // 9. Consider DropBox entries
4284            // TODO: Implement
4285
4286            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4287            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4288                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4289                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4290                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4291                return;
4292            }
4293        } else {
4294            try {
4295                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4296            } catch (InstallerException ignored) {
4297            }
4298            if (file.getUsableSpace() >= bytes) return;
4299        }
4300
4301        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4302    }
4303
4304    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4305            throws IOException {
4306        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4307        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4308
4309        List<VersionedPackage> packagesToDelete = null;
4310        final long now = System.currentTimeMillis();
4311
4312        synchronized (mPackages) {
4313            final int[] allUsers = sUserManager.getUserIds();
4314            final int libCount = mSharedLibraries.size();
4315            for (int i = 0; i < libCount; i++) {
4316                final SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4317                if (versionedLib == null) {
4318                    continue;
4319                }
4320                final int versionCount = versionedLib.size();
4321                for (int j = 0; j < versionCount; j++) {
4322                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4323                    // Skip packages that are not static shared libs.
4324                    if (!libInfo.isStatic()) {
4325                        break;
4326                    }
4327                    // Important: We skip static shared libs used for some user since
4328                    // in such a case we need to keep the APK on the device. The check for
4329                    // a lib being used for any user is performed by the uninstall call.
4330                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4331                    // Resolve the package name - we use synthetic package names internally
4332                    final String internalPackageName = resolveInternalPackageNameLPr(
4333                            declaringPackage.getPackageName(), declaringPackage.getVersionCode());
4334                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4335                    // Skip unused static shared libs cached less than the min period
4336                    // to prevent pruning a lib needed by a subsequently installed package.
4337                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4338                        continue;
4339                    }
4340                    if (packagesToDelete == null) {
4341                        packagesToDelete = new ArrayList<>();
4342                    }
4343                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4344                            declaringPackage.getVersionCode()));
4345                }
4346            }
4347        }
4348
4349        if (packagesToDelete != null) {
4350            final int packageCount = packagesToDelete.size();
4351            for (int i = 0; i < packageCount; i++) {
4352                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4353                // Delete the package synchronously (will fail of the lib used for any user).
4354                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getVersionCode(),
4355                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4356                                == PackageManager.DELETE_SUCCEEDED) {
4357                    if (volume.getUsableSpace() >= neededSpace) {
4358                        return true;
4359                    }
4360                }
4361            }
4362        }
4363
4364        return false;
4365    }
4366
4367    /**
4368     * Update given flags based on encryption status of current user.
4369     */
4370    private int updateFlags(int flags, int userId) {
4371        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4372                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4373            // Caller expressed an explicit opinion about what encryption
4374            // aware/unaware components they want to see, so fall through and
4375            // give them what they want
4376        } else {
4377            // Caller expressed no opinion, so match based on user state
4378            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4379                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4380            } else {
4381                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4382            }
4383        }
4384        return flags;
4385    }
4386
4387    private UserManagerInternal getUserManagerInternal() {
4388        if (mUserManagerInternal == null) {
4389            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4390        }
4391        return mUserManagerInternal;
4392    }
4393
4394    private DeviceIdleController.LocalService getDeviceIdleController() {
4395        if (mDeviceIdleController == null) {
4396            mDeviceIdleController =
4397                    LocalServices.getService(DeviceIdleController.LocalService.class);
4398        }
4399        return mDeviceIdleController;
4400    }
4401
4402    /**
4403     * Update given flags when being used to request {@link PackageInfo}.
4404     */
4405    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4406        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4407        boolean triaged = true;
4408        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4409                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4410            // Caller is asking for component details, so they'd better be
4411            // asking for specific encryption matching behavior, or be triaged
4412            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4413                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4414                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4415                triaged = false;
4416            }
4417        }
4418        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4419                | PackageManager.MATCH_SYSTEM_ONLY
4420                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4421            triaged = false;
4422        }
4423        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4424            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
4425                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4426                    + Debug.getCallers(5));
4427        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4428                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4429            // If the caller wants all packages and has a restricted profile associated with it,
4430            // then match all users. This is to make sure that launchers that need to access work
4431            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4432            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4433            flags |= PackageManager.MATCH_ANY_USER;
4434        }
4435        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4436            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4437                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4438        }
4439        return updateFlags(flags, userId);
4440    }
4441
4442    /**
4443     * Update given flags when being used to request {@link ApplicationInfo}.
4444     */
4445    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4446        return updateFlagsForPackage(flags, userId, cookie);
4447    }
4448
4449    /**
4450     * Update given flags when being used to request {@link ComponentInfo}.
4451     */
4452    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4453        if (cookie instanceof Intent) {
4454            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4455                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4456            }
4457        }
4458
4459        boolean triaged = true;
4460        // Caller is asking for component details, so they'd better be
4461        // asking for specific encryption matching behavior, or be triaged
4462        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4463                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4464                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4465            triaged = false;
4466        }
4467        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4468            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4469                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4470        }
4471
4472        return updateFlags(flags, userId);
4473    }
4474
4475    /**
4476     * Update given intent when being used to request {@link ResolveInfo}.
4477     */
4478    private Intent updateIntentForResolve(Intent intent) {
4479        if (intent.getSelector() != null) {
4480            intent = intent.getSelector();
4481        }
4482        if (DEBUG_PREFERRED) {
4483            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4484        }
4485        return intent;
4486    }
4487
4488    /**
4489     * Update given flags when being used to request {@link ResolveInfo}.
4490     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4491     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4492     * flag set. However, this flag is only honoured in three circumstances:
4493     * <ul>
4494     * <li>when called from a system process</li>
4495     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4496     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4497     * action and a {@code android.intent.category.BROWSABLE} category</li>
4498     * </ul>
4499     */
4500    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4501        return updateFlagsForResolve(flags, userId, intent, callingUid,
4502                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4503    }
4504    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4505            boolean wantInstantApps) {
4506        return updateFlagsForResolve(flags, userId, intent, callingUid,
4507                wantInstantApps, false /*onlyExposedExplicitly*/);
4508    }
4509    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4510            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4511        // Safe mode means we shouldn't match any third-party components
4512        if (mSafeMode) {
4513            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4514        }
4515        if (getInstantAppPackageName(callingUid) != null) {
4516            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4517            if (onlyExposedExplicitly) {
4518                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4519            }
4520            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4521            flags |= PackageManager.MATCH_INSTANT;
4522        } else {
4523            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4524            final boolean allowMatchInstant =
4525                    (wantInstantApps
4526                            && Intent.ACTION_VIEW.equals(intent.getAction())
4527                            && hasWebURI(intent))
4528                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4529            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4530                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4531            if (!allowMatchInstant) {
4532                flags &= ~PackageManager.MATCH_INSTANT;
4533            }
4534        }
4535        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4536    }
4537
4538    @Override
4539    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4540        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4541    }
4542
4543    /**
4544     * Important: The provided filterCallingUid is used exclusively to filter out activities
4545     * that can be seen based on user state. It's typically the original caller uid prior
4546     * to clearing. Because it can only be provided by trusted code, it's value can be
4547     * trusted and will be used as-is; unlike userId which will be validated by this method.
4548     */
4549    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4550            int filterCallingUid, int userId) {
4551        if (!sUserManager.exists(userId)) return null;
4552        flags = updateFlagsForComponent(flags, userId, component);
4553        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4554                false /* requireFullPermission */, false /* checkShell */, "get activity info");
4555        synchronized (mPackages) {
4556            PackageParser.Activity a = mActivities.mActivities.get(component);
4557
4558            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4559            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4560                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4561                if (ps == null) return null;
4562                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4563                    return null;
4564                }
4565                return PackageParser.generateActivityInfo(
4566                        a, flags, ps.readUserState(userId), userId);
4567            }
4568            if (mResolveComponentName.equals(component)) {
4569                return PackageParser.generateActivityInfo(
4570                        mResolveActivity, flags, new PackageUserState(), userId);
4571            }
4572        }
4573        return null;
4574    }
4575
4576    @Override
4577    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4578            String resolvedType) {
4579        synchronized (mPackages) {
4580            if (component.equals(mResolveComponentName)) {
4581                // The resolver supports EVERYTHING!
4582                return true;
4583            }
4584            final int callingUid = Binder.getCallingUid();
4585            final int callingUserId = UserHandle.getUserId(callingUid);
4586            PackageParser.Activity a = mActivities.mActivities.get(component);
4587            if (a == null) {
4588                return false;
4589            }
4590            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4591            if (ps == null) {
4592                return false;
4593            }
4594            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4595                return false;
4596            }
4597            for (int i=0; i<a.intents.size(); i++) {
4598                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4599                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4600                    return true;
4601                }
4602            }
4603            return false;
4604        }
4605    }
4606
4607    @Override
4608    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4609        if (!sUserManager.exists(userId)) return null;
4610        final int callingUid = Binder.getCallingUid();
4611        flags = updateFlagsForComponent(flags, userId, component);
4612        enforceCrossUserPermission(callingUid, userId,
4613                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4614        synchronized (mPackages) {
4615            PackageParser.Activity a = mReceivers.mActivities.get(component);
4616            if (DEBUG_PACKAGE_INFO) Log.v(
4617                TAG, "getReceiverInfo " + component + ": " + a);
4618            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4619                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4620                if (ps == null) return null;
4621                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4622                    return null;
4623                }
4624                return PackageParser.generateActivityInfo(
4625                        a, flags, ps.readUserState(userId), userId);
4626            }
4627        }
4628        return null;
4629    }
4630
4631    @Override
4632    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4633            int flags, int userId) {
4634        if (!sUserManager.exists(userId)) return null;
4635        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4636        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4637            return null;
4638        }
4639
4640        flags = updateFlagsForPackage(flags, userId, null);
4641
4642        final boolean canSeeStaticLibraries =
4643                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4644                        == PERMISSION_GRANTED
4645                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4646                        == PERMISSION_GRANTED
4647                || canRequestPackageInstallsInternal(packageName,
4648                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
4649                        false  /* throwIfPermNotDeclared*/)
4650                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4651                        == PERMISSION_GRANTED;
4652
4653        synchronized (mPackages) {
4654            List<SharedLibraryInfo> result = null;
4655
4656            final int libCount = mSharedLibraries.size();
4657            for (int i = 0; i < libCount; i++) {
4658                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4659                if (versionedLib == null) {
4660                    continue;
4661                }
4662
4663                final int versionCount = versionedLib.size();
4664                for (int j = 0; j < versionCount; j++) {
4665                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4666                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4667                        break;
4668                    }
4669                    final long identity = Binder.clearCallingIdentity();
4670                    try {
4671                        PackageInfo packageInfo = getPackageInfoVersioned(
4672                                libInfo.getDeclaringPackage(), flags
4673                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
4674                        if (packageInfo == null) {
4675                            continue;
4676                        }
4677                    } finally {
4678                        Binder.restoreCallingIdentity(identity);
4679                    }
4680
4681                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4682                            libInfo.getVersion(), libInfo.getType(),
4683                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
4684                            flags, userId));
4685
4686                    if (result == null) {
4687                        result = new ArrayList<>();
4688                    }
4689                    result.add(resLibInfo);
4690                }
4691            }
4692
4693            return result != null ? new ParceledListSlice<>(result) : null;
4694        }
4695    }
4696
4697    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4698            SharedLibraryInfo libInfo, int flags, int userId) {
4699        List<VersionedPackage> versionedPackages = null;
4700        final int packageCount = mSettings.mPackages.size();
4701        for (int i = 0; i < packageCount; i++) {
4702            PackageSetting ps = mSettings.mPackages.valueAt(i);
4703
4704            if (ps == null) {
4705                continue;
4706            }
4707
4708            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4709                continue;
4710            }
4711
4712            final String libName = libInfo.getName();
4713            if (libInfo.isStatic()) {
4714                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4715                if (libIdx < 0) {
4716                    continue;
4717                }
4718                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
4719                    continue;
4720                }
4721                if (versionedPackages == null) {
4722                    versionedPackages = new ArrayList<>();
4723                }
4724                // If the dependent is a static shared lib, use the public package name
4725                String dependentPackageName = ps.name;
4726                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4727                    dependentPackageName = ps.pkg.manifestPackageName;
4728                }
4729                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
4730            } else if (ps.pkg != null) {
4731                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
4732                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
4733                    if (versionedPackages == null) {
4734                        versionedPackages = new ArrayList<>();
4735                    }
4736                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
4737                }
4738            }
4739        }
4740
4741        return versionedPackages;
4742    }
4743
4744    @Override
4745    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
4746        if (!sUserManager.exists(userId)) return null;
4747        final int callingUid = Binder.getCallingUid();
4748        flags = updateFlagsForComponent(flags, userId, component);
4749        enforceCrossUserPermission(callingUid, userId,
4750                false /* requireFullPermission */, false /* checkShell */, "get service info");
4751        synchronized (mPackages) {
4752            PackageParser.Service s = mServices.mServices.get(component);
4753            if (DEBUG_PACKAGE_INFO) Log.v(
4754                TAG, "getServiceInfo " + component + ": " + s);
4755            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
4756                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4757                if (ps == null) return null;
4758                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
4759                    return null;
4760                }
4761                return PackageParser.generateServiceInfo(
4762                        s, flags, ps.readUserState(userId), userId);
4763            }
4764        }
4765        return null;
4766    }
4767
4768    @Override
4769    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
4770        if (!sUserManager.exists(userId)) return null;
4771        final int callingUid = Binder.getCallingUid();
4772        flags = updateFlagsForComponent(flags, userId, component);
4773        enforceCrossUserPermission(callingUid, userId,
4774                false /* requireFullPermission */, false /* checkShell */, "get provider info");
4775        synchronized (mPackages) {
4776            PackageParser.Provider p = mProviders.mProviders.get(component);
4777            if (DEBUG_PACKAGE_INFO) Log.v(
4778                TAG, "getProviderInfo " + component + ": " + p);
4779            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
4780                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4781                if (ps == null) return null;
4782                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
4783                    return null;
4784                }
4785                return PackageParser.generateProviderInfo(
4786                        p, flags, ps.readUserState(userId), userId);
4787            }
4788        }
4789        return null;
4790    }
4791
4792    @Override
4793    public String[] getSystemSharedLibraryNames() {
4794        // allow instant applications
4795        synchronized (mPackages) {
4796            Set<String> libs = null;
4797            final int libCount = mSharedLibraries.size();
4798            for (int i = 0; i < libCount; i++) {
4799                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4800                if (versionedLib == null) {
4801                    continue;
4802                }
4803                final int versionCount = versionedLib.size();
4804                for (int j = 0; j < versionCount; j++) {
4805                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
4806                    if (!libEntry.info.isStatic()) {
4807                        if (libs == null) {
4808                            libs = new ArraySet<>();
4809                        }
4810                        libs.add(libEntry.info.getName());
4811                        break;
4812                    }
4813                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
4814                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
4815                            UserHandle.getUserId(Binder.getCallingUid()),
4816                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
4817                        if (libs == null) {
4818                            libs = new ArraySet<>();
4819                        }
4820                        libs.add(libEntry.info.getName());
4821                        break;
4822                    }
4823                }
4824            }
4825
4826            if (libs != null) {
4827                String[] libsArray = new String[libs.size()];
4828                libs.toArray(libsArray);
4829                return libsArray;
4830            }
4831
4832            return null;
4833        }
4834    }
4835
4836    @Override
4837    public @NonNull String getServicesSystemSharedLibraryPackageName() {
4838        // allow instant applications
4839        synchronized (mPackages) {
4840            return mServicesSystemSharedLibraryPackageName;
4841        }
4842    }
4843
4844    @Override
4845    public @NonNull String getSharedSystemSharedLibraryPackageName() {
4846        // allow instant applications
4847        synchronized (mPackages) {
4848            return mSharedSystemSharedLibraryPackageName;
4849        }
4850    }
4851
4852    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
4853        for (int i = userList.length - 1; i >= 0; --i) {
4854            final int userId = userList[i];
4855            // don't add instant app to the list of updates
4856            if (pkgSetting.getInstantApp(userId)) {
4857                continue;
4858            }
4859            SparseArray<String> changedPackages = mChangedPackages.get(userId);
4860            if (changedPackages == null) {
4861                changedPackages = new SparseArray<>();
4862                mChangedPackages.put(userId, changedPackages);
4863            }
4864            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
4865            if (sequenceNumbers == null) {
4866                sequenceNumbers = new HashMap<>();
4867                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
4868            }
4869            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
4870            if (sequenceNumber != null) {
4871                changedPackages.remove(sequenceNumber);
4872            }
4873            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
4874            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
4875        }
4876        mChangedPackagesSequenceNumber++;
4877    }
4878
4879    @Override
4880    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
4881        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4882            return null;
4883        }
4884        synchronized (mPackages) {
4885            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
4886                return null;
4887            }
4888            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
4889            if (changedPackages == null) {
4890                return null;
4891            }
4892            final List<String> packageNames =
4893                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
4894            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
4895                final String packageName = changedPackages.get(i);
4896                if (packageName != null) {
4897                    packageNames.add(packageName);
4898                }
4899            }
4900            return packageNames.isEmpty()
4901                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
4902        }
4903    }
4904
4905    @Override
4906    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
4907        // allow instant applications
4908        ArrayList<FeatureInfo> res;
4909        synchronized (mAvailableFeatures) {
4910            res = new ArrayList<>(mAvailableFeatures.size() + 1);
4911            res.addAll(mAvailableFeatures.values());
4912        }
4913        final FeatureInfo fi = new FeatureInfo();
4914        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
4915                FeatureInfo.GL_ES_VERSION_UNDEFINED);
4916        res.add(fi);
4917
4918        return new ParceledListSlice<>(res);
4919    }
4920
4921    @Override
4922    public boolean hasSystemFeature(String name, int version) {
4923        // allow instant applications
4924        synchronized (mAvailableFeatures) {
4925            final FeatureInfo feat = mAvailableFeatures.get(name);
4926            if (feat == null) {
4927                return false;
4928            } else {
4929                return feat.version >= version;
4930            }
4931        }
4932    }
4933
4934    @Override
4935    public int checkPermission(String permName, String pkgName, int userId) {
4936        if (!sUserManager.exists(userId)) {
4937            return PackageManager.PERMISSION_DENIED;
4938        }
4939        final int callingUid = Binder.getCallingUid();
4940
4941        synchronized (mPackages) {
4942            final PackageParser.Package p = mPackages.get(pkgName);
4943            if (p != null && p.mExtras != null) {
4944                final PackageSetting ps = (PackageSetting) p.mExtras;
4945                if (filterAppAccessLPr(ps, callingUid, userId)) {
4946                    return PackageManager.PERMISSION_DENIED;
4947                }
4948                final boolean instantApp = ps.getInstantApp(userId);
4949                final PermissionsState permissionsState = ps.getPermissionsState();
4950                if (permissionsState.hasPermission(permName, userId)) {
4951                    if (instantApp) {
4952                        BasePermission bp = mSettings.mPermissions.get(permName);
4953                        if (bp != null && bp.isInstant()) {
4954                            return PackageManager.PERMISSION_GRANTED;
4955                        }
4956                    } else {
4957                        return PackageManager.PERMISSION_GRANTED;
4958                    }
4959                }
4960                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
4961                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
4962                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
4963                    return PackageManager.PERMISSION_GRANTED;
4964                }
4965            }
4966        }
4967
4968        return PackageManager.PERMISSION_DENIED;
4969    }
4970
4971    @Override
4972    public int checkUidPermission(String permName, int uid) {
4973        final int callingUid = Binder.getCallingUid();
4974        final int callingUserId = UserHandle.getUserId(callingUid);
4975        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
4976        final boolean isUidInstantApp = getInstantAppPackageName(uid) != null;
4977        final int userId = UserHandle.getUserId(uid);
4978        if (!sUserManager.exists(userId)) {
4979            return PackageManager.PERMISSION_DENIED;
4980        }
4981
4982        synchronized (mPackages) {
4983            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4984            if (obj != null) {
4985                if (obj instanceof SharedUserSetting) {
4986                    if (isCallerInstantApp) {
4987                        return PackageManager.PERMISSION_DENIED;
4988                    }
4989                } else if (obj instanceof PackageSetting) {
4990                    final PackageSetting ps = (PackageSetting) obj;
4991                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
4992                        return PackageManager.PERMISSION_DENIED;
4993                    }
4994                }
4995                final SettingBase settingBase = (SettingBase) obj;
4996                final PermissionsState permissionsState = settingBase.getPermissionsState();
4997                if (permissionsState.hasPermission(permName, userId)) {
4998                    if (isUidInstantApp) {
4999                        BasePermission bp = mSettings.mPermissions.get(permName);
5000                        if (bp != null && bp.isInstant()) {
5001                            return PackageManager.PERMISSION_GRANTED;
5002                        }
5003                    } else {
5004                        return PackageManager.PERMISSION_GRANTED;
5005                    }
5006                }
5007                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5008                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5009                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5010                    return PackageManager.PERMISSION_GRANTED;
5011                }
5012            } else {
5013                ArraySet<String> perms = mSystemPermissions.get(uid);
5014                if (perms != null) {
5015                    if (perms.contains(permName)) {
5016                        return PackageManager.PERMISSION_GRANTED;
5017                    }
5018                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
5019                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
5020                        return PackageManager.PERMISSION_GRANTED;
5021                    }
5022                }
5023            }
5024        }
5025
5026        return PackageManager.PERMISSION_DENIED;
5027    }
5028
5029    @Override
5030    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5031        if (UserHandle.getCallingUserId() != userId) {
5032            mContext.enforceCallingPermission(
5033                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5034                    "isPermissionRevokedByPolicy for user " + userId);
5035        }
5036
5037        if (checkPermission(permission, packageName, userId)
5038                == PackageManager.PERMISSION_GRANTED) {
5039            return false;
5040        }
5041
5042        final int callingUid = Binder.getCallingUid();
5043        if (getInstantAppPackageName(callingUid) != null) {
5044            if (!isCallerSameApp(packageName, callingUid)) {
5045                return false;
5046            }
5047        } else {
5048            if (isInstantApp(packageName, userId)) {
5049                return false;
5050            }
5051        }
5052
5053        final long identity = Binder.clearCallingIdentity();
5054        try {
5055            final int flags = getPermissionFlags(permission, packageName, userId);
5056            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5057        } finally {
5058            Binder.restoreCallingIdentity(identity);
5059        }
5060    }
5061
5062    @Override
5063    public String getPermissionControllerPackageName() {
5064        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5065            throw new SecurityException("Instant applications don't have access to this method");
5066        }
5067        synchronized (mPackages) {
5068            return mRequiredInstallerPackage;
5069        }
5070    }
5071
5072    /**
5073     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
5074     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
5075     * @param checkShell whether to prevent shell from access if there's a debugging restriction
5076     * @param message the message to log on security exception
5077     */
5078    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
5079            boolean checkShell, String message) {
5080        if (userId < 0) {
5081            throw new IllegalArgumentException("Invalid userId " + userId);
5082        }
5083        if (checkShell) {
5084            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
5085        }
5086        if (userId == UserHandle.getUserId(callingUid)) return;
5087        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5088            if (requireFullPermission) {
5089                mContext.enforceCallingOrSelfPermission(
5090                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5091            } else {
5092                try {
5093                    mContext.enforceCallingOrSelfPermission(
5094                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5095                } catch (SecurityException se) {
5096                    mContext.enforceCallingOrSelfPermission(
5097                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
5098                }
5099            }
5100        }
5101    }
5102
5103    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
5104        if (callingUid == Process.SHELL_UID) {
5105            if (userHandle >= 0
5106                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
5107                throw new SecurityException("Shell does not have permission to access user "
5108                        + userHandle);
5109            } else if (userHandle < 0) {
5110                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
5111                        + Debug.getCallers(3));
5112            }
5113        }
5114    }
5115
5116    private BasePermission findPermissionTreeLP(String permName) {
5117        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
5118            if (permName.startsWith(bp.name) &&
5119                    permName.length() > bp.name.length() &&
5120                    permName.charAt(bp.name.length()) == '.') {
5121                return bp;
5122            }
5123        }
5124        return null;
5125    }
5126
5127    private BasePermission checkPermissionTreeLP(String permName) {
5128        if (permName != null) {
5129            BasePermission bp = findPermissionTreeLP(permName);
5130            if (bp != null) {
5131                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
5132                    return bp;
5133                }
5134                throw new SecurityException("Calling uid "
5135                        + Binder.getCallingUid()
5136                        + " is not allowed to add to permission tree "
5137                        + bp.name + " owned by uid " + bp.uid);
5138            }
5139        }
5140        throw new SecurityException("No permission tree found for " + permName);
5141    }
5142
5143    static boolean compareStrings(CharSequence s1, CharSequence s2) {
5144        if (s1 == null) {
5145            return s2 == null;
5146        }
5147        if (s2 == null) {
5148            return false;
5149        }
5150        if (s1.getClass() != s2.getClass()) {
5151            return false;
5152        }
5153        return s1.equals(s2);
5154    }
5155
5156    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
5157        if (pi1.icon != pi2.icon) return false;
5158        if (pi1.logo != pi2.logo) return false;
5159        if (pi1.protectionLevel != pi2.protectionLevel) return false;
5160        if (!compareStrings(pi1.name, pi2.name)) return false;
5161        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
5162        // We'll take care of setting this one.
5163        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
5164        // These are not currently stored in settings.
5165        //if (!compareStrings(pi1.group, pi2.group)) return false;
5166        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
5167        //if (pi1.labelRes != pi2.labelRes) return false;
5168        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
5169        return true;
5170    }
5171
5172    int permissionInfoFootprint(PermissionInfo info) {
5173        int size = info.name.length();
5174        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
5175        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
5176        return size;
5177    }
5178
5179    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
5180        int size = 0;
5181        for (BasePermission perm : mSettings.mPermissions.values()) {
5182            if (perm.uid == tree.uid) {
5183                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
5184            }
5185        }
5186        return size;
5187    }
5188
5189    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
5190        // We calculate the max size of permissions defined by this uid and throw
5191        // if that plus the size of 'info' would exceed our stated maximum.
5192        if (tree.uid != Process.SYSTEM_UID) {
5193            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
5194            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
5195                throw new SecurityException("Permission tree size cap exceeded");
5196            }
5197        }
5198    }
5199
5200    boolean addPermissionLocked(PermissionInfo info, boolean async) {
5201        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5202            throw new SecurityException("Instant apps can't add permissions");
5203        }
5204        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
5205            throw new SecurityException("Label must be specified in permission");
5206        }
5207        BasePermission tree = checkPermissionTreeLP(info.name);
5208        BasePermission bp = mSettings.mPermissions.get(info.name);
5209        boolean added = bp == null;
5210        boolean changed = true;
5211        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
5212        if (added) {
5213            enforcePermissionCapLocked(info, tree);
5214            bp = new BasePermission(info.name, tree.sourcePackage,
5215                    BasePermission.TYPE_DYNAMIC);
5216        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
5217            throw new SecurityException(
5218                    "Not allowed to modify non-dynamic permission "
5219                    + info.name);
5220        } else {
5221            if (bp.protectionLevel == fixedLevel
5222                    && bp.perm.owner.equals(tree.perm.owner)
5223                    && bp.uid == tree.uid
5224                    && comparePermissionInfos(bp.perm.info, info)) {
5225                changed = false;
5226            }
5227        }
5228        bp.protectionLevel = fixedLevel;
5229        info = new PermissionInfo(info);
5230        info.protectionLevel = fixedLevel;
5231        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
5232        bp.perm.info.packageName = tree.perm.info.packageName;
5233        bp.uid = tree.uid;
5234        if (added) {
5235            mSettings.mPermissions.put(info.name, bp);
5236        }
5237        if (changed) {
5238            if (!async) {
5239                mSettings.writeLPr();
5240            } else {
5241                scheduleWriteSettingsLocked();
5242            }
5243        }
5244        return added;
5245    }
5246
5247    @Override
5248    public boolean addPermission(PermissionInfo info) {
5249        synchronized (mPackages) {
5250            return addPermissionLocked(info, false);
5251        }
5252    }
5253
5254    @Override
5255    public boolean addPermissionAsync(PermissionInfo info) {
5256        synchronized (mPackages) {
5257            return addPermissionLocked(info, true);
5258        }
5259    }
5260
5261    @Override
5262    public void removePermission(String name) {
5263        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5264            throw new SecurityException("Instant applications don't have access to this method");
5265        }
5266        synchronized (mPackages) {
5267            checkPermissionTreeLP(name);
5268            BasePermission bp = mSettings.mPermissions.get(name);
5269            if (bp != null) {
5270                if (bp.type != BasePermission.TYPE_DYNAMIC) {
5271                    throw new SecurityException(
5272                            "Not allowed to modify non-dynamic permission "
5273                            + name);
5274                }
5275                mSettings.mPermissions.remove(name);
5276                mSettings.writeLPr();
5277            }
5278        }
5279    }
5280
5281    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(
5282            PackageParser.Package pkg, BasePermission bp) {
5283        int index = pkg.requestedPermissions.indexOf(bp.name);
5284        if (index == -1) {
5285            throw new SecurityException("Package " + pkg.packageName
5286                    + " has not requested permission " + bp.name);
5287        }
5288        if (!bp.isRuntime() && !bp.isDevelopment()) {
5289            throw new SecurityException("Permission " + bp.name
5290                    + " is not a changeable permission type");
5291        }
5292    }
5293
5294    @Override
5295    public void grantRuntimePermission(String packageName, String name, final int userId) {
5296        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5297    }
5298
5299    private void grantRuntimePermission(String packageName, String name, final int userId,
5300            boolean overridePolicy) {
5301        if (!sUserManager.exists(userId)) {
5302            Log.e(TAG, "No such user:" + userId);
5303            return;
5304        }
5305        final int callingUid = Binder.getCallingUid();
5306
5307        mContext.enforceCallingOrSelfPermission(
5308                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
5309                "grantRuntimePermission");
5310
5311        enforceCrossUserPermission(callingUid, userId,
5312                true /* requireFullPermission */, true /* checkShell */,
5313                "grantRuntimePermission");
5314
5315        final int uid;
5316        final PackageSetting ps;
5317
5318        synchronized (mPackages) {
5319            final PackageParser.Package pkg = mPackages.get(packageName);
5320            if (pkg == null) {
5321                throw new IllegalArgumentException("Unknown package: " + packageName);
5322            }
5323            final BasePermission bp = mSettings.mPermissions.get(name);
5324            if (bp == null) {
5325                throw new IllegalArgumentException("Unknown permission: " + name);
5326            }
5327            ps = (PackageSetting) pkg.mExtras;
5328            if (ps == null
5329                    || filterAppAccessLPr(ps, callingUid, userId)) {
5330                throw new IllegalArgumentException("Unknown package: " + packageName);
5331            }
5332
5333            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5334
5335            // If a permission review is required for legacy apps we represent
5336            // their permissions as always granted runtime ones since we need
5337            // to keep the review required permission flag per user while an
5338            // install permission's state is shared across all users.
5339            if (mPermissionReviewRequired
5340                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5341                    && bp.isRuntime()) {
5342                return;
5343            }
5344
5345            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
5346
5347            final PermissionsState permissionsState = ps.getPermissionsState();
5348
5349            final int flags = permissionsState.getPermissionFlags(name, userId);
5350            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5351                throw new SecurityException("Cannot grant system fixed permission "
5352                        + name + " for package " + packageName);
5353            }
5354            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5355                throw new SecurityException("Cannot grant policy fixed permission "
5356                        + name + " for package " + packageName);
5357            }
5358
5359            if (bp.isDevelopment()) {
5360                // Development permissions must be handled specially, since they are not
5361                // normal runtime permissions.  For now they apply to all users.
5362                if (permissionsState.grantInstallPermission(bp) !=
5363                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5364                    scheduleWriteSettingsLocked();
5365                }
5366                return;
5367            }
5368
5369            if (ps.getInstantApp(userId) && !bp.isInstant()) {
5370                throw new SecurityException("Cannot grant non-ephemeral permission"
5371                        + name + " for package " + packageName);
5372            }
5373
5374            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
5375                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
5376                return;
5377            }
5378
5379            final int result = permissionsState.grantRuntimePermission(bp, userId);
5380            switch (result) {
5381                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
5382                    return;
5383                }
5384
5385                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
5386                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5387                    mHandler.post(new Runnable() {
5388                        @Override
5389                        public void run() {
5390                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
5391                        }
5392                    });
5393                }
5394                break;
5395            }
5396
5397            if (bp.isRuntime()) {
5398                logPermissionGranted(mContext, name, packageName);
5399            }
5400
5401            mOnPermissionChangeListeners.onPermissionsChanged(uid);
5402
5403            // Not critical if that is lost - app has to request again.
5404            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5405        }
5406
5407        // Only need to do this if user is initialized. Otherwise it's a new user
5408        // and there are no processes running as the user yet and there's no need
5409        // to make an expensive call to remount processes for the changed permissions.
5410        if (READ_EXTERNAL_STORAGE.equals(name)
5411                || WRITE_EXTERNAL_STORAGE.equals(name)) {
5412            final long token = Binder.clearCallingIdentity();
5413            try {
5414                if (sUserManager.isInitialized(userId)) {
5415                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
5416                            StorageManagerInternal.class);
5417                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
5418                }
5419            } finally {
5420                Binder.restoreCallingIdentity(token);
5421            }
5422        }
5423    }
5424
5425    @Override
5426    public void revokeRuntimePermission(String packageName, String name, int userId) {
5427        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5428    }
5429
5430    private void revokeRuntimePermission(String packageName, String name, int userId,
5431            boolean overridePolicy) {
5432        if (!sUserManager.exists(userId)) {
5433            Log.e(TAG, "No such user:" + userId);
5434            return;
5435        }
5436
5437        mContext.enforceCallingOrSelfPermission(
5438                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5439                "revokeRuntimePermission");
5440
5441        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5442                true /* requireFullPermission */, true /* checkShell */,
5443                "revokeRuntimePermission");
5444
5445        final int appId;
5446
5447        synchronized (mPackages) {
5448            final PackageParser.Package pkg = mPackages.get(packageName);
5449            if (pkg == null) {
5450                throw new IllegalArgumentException("Unknown package: " + packageName);
5451            }
5452            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5453            if (ps == null
5454                    || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
5455                throw new IllegalArgumentException("Unknown package: " + packageName);
5456            }
5457            final BasePermission bp = mSettings.mPermissions.get(name);
5458            if (bp == null) {
5459                throw new IllegalArgumentException("Unknown permission: " + name);
5460            }
5461
5462            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5463
5464            // If a permission review is required for legacy apps we represent
5465            // their permissions as always granted runtime ones since we need
5466            // to keep the review required permission flag per user while an
5467            // install permission's state is shared across all users.
5468            if (mPermissionReviewRequired
5469                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5470                    && bp.isRuntime()) {
5471                return;
5472            }
5473
5474            final PermissionsState permissionsState = ps.getPermissionsState();
5475
5476            final int flags = permissionsState.getPermissionFlags(name, userId);
5477            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5478                throw new SecurityException("Cannot revoke system fixed permission "
5479                        + name + " for package " + packageName);
5480            }
5481            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5482                throw new SecurityException("Cannot revoke policy fixed permission "
5483                        + name + " for package " + packageName);
5484            }
5485
5486            if (bp.isDevelopment()) {
5487                // Development permissions must be handled specially, since they are not
5488                // normal runtime permissions.  For now they apply to all users.
5489                if (permissionsState.revokeInstallPermission(bp) !=
5490                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5491                    scheduleWriteSettingsLocked();
5492                }
5493                return;
5494            }
5495
5496            if (permissionsState.revokeRuntimePermission(bp, userId) ==
5497                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
5498                return;
5499            }
5500
5501            if (bp.isRuntime()) {
5502                logPermissionRevoked(mContext, name, packageName);
5503            }
5504
5505            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
5506
5507            // Critical, after this call app should never have the permission.
5508            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
5509
5510            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5511        }
5512
5513        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
5514    }
5515
5516    /**
5517     * Get the first event id for the permission.
5518     *
5519     * <p>There are four events for each permission: <ul>
5520     *     <li>Request permission: first id + 0</li>
5521     *     <li>Grant permission: first id + 1</li>
5522     *     <li>Request for permission denied: first id + 2</li>
5523     *     <li>Revoke permission: first id + 3</li>
5524     * </ul></p>
5525     *
5526     * @param name name of the permission
5527     *
5528     * @return The first event id for the permission
5529     */
5530    private static int getBaseEventId(@NonNull String name) {
5531        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
5532
5533        if (eventIdIndex == -1) {
5534            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
5535                    || "user".equals(Build.TYPE)) {
5536                Log.i(TAG, "Unknown permission " + name);
5537
5538                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
5539            } else {
5540                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
5541                //
5542                // Also update
5543                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
5544                // - metrics_constants.proto
5545                throw new IllegalStateException("Unknown permission " + name);
5546            }
5547        }
5548
5549        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
5550    }
5551
5552    /**
5553     * Log that a permission was revoked.
5554     *
5555     * @param context Context of the caller
5556     * @param name name of the permission
5557     * @param packageName package permission if for
5558     */
5559    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
5560            @NonNull String packageName) {
5561        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
5562    }
5563
5564    /**
5565     * Log that a permission request was granted.
5566     *
5567     * @param context Context of the caller
5568     * @param name name of the permission
5569     * @param packageName package permission if for
5570     */
5571    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
5572            @NonNull String packageName) {
5573        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
5574    }
5575
5576    @Override
5577    public void resetRuntimePermissions() {
5578        mContext.enforceCallingOrSelfPermission(
5579                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5580                "revokeRuntimePermission");
5581
5582        int callingUid = Binder.getCallingUid();
5583        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5584            mContext.enforceCallingOrSelfPermission(
5585                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5586                    "resetRuntimePermissions");
5587        }
5588
5589        synchronized (mPackages) {
5590            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
5591            for (int userId : UserManagerService.getInstance().getUserIds()) {
5592                final int packageCount = mPackages.size();
5593                for (int i = 0; i < packageCount; i++) {
5594                    PackageParser.Package pkg = mPackages.valueAt(i);
5595                    if (!(pkg.mExtras instanceof PackageSetting)) {
5596                        continue;
5597                    }
5598                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5599                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5600                }
5601            }
5602        }
5603    }
5604
5605    @Override
5606    public int getPermissionFlags(String name, String packageName, int userId) {
5607        if (!sUserManager.exists(userId)) {
5608            return 0;
5609        }
5610
5611        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
5612
5613        final int callingUid = Binder.getCallingUid();
5614        enforceCrossUserPermission(callingUid, userId,
5615                true /* requireFullPermission */, false /* checkShell */,
5616                "getPermissionFlags");
5617
5618        synchronized (mPackages) {
5619            final PackageParser.Package pkg = mPackages.get(packageName);
5620            if (pkg == null) {
5621                return 0;
5622            }
5623            final BasePermission bp = mSettings.mPermissions.get(name);
5624            if (bp == null) {
5625                return 0;
5626            }
5627            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5628            if (ps == null
5629                    || filterAppAccessLPr(ps, callingUid, userId)) {
5630                return 0;
5631            }
5632            PermissionsState permissionsState = ps.getPermissionsState();
5633            return permissionsState.getPermissionFlags(name, userId);
5634        }
5635    }
5636
5637    @Override
5638    public void updatePermissionFlags(String name, String packageName, int flagMask,
5639            int flagValues, int userId) {
5640        if (!sUserManager.exists(userId)) {
5641            return;
5642        }
5643
5644        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
5645
5646        final int callingUid = Binder.getCallingUid();
5647        enforceCrossUserPermission(callingUid, userId,
5648                true /* requireFullPermission */, true /* checkShell */,
5649                "updatePermissionFlags");
5650
5651        // Only the system can change these flags and nothing else.
5652        if (getCallingUid() != Process.SYSTEM_UID) {
5653            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5654            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5655            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5656            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5657            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
5658        }
5659
5660        synchronized (mPackages) {
5661            final PackageParser.Package pkg = mPackages.get(packageName);
5662            if (pkg == null) {
5663                throw new IllegalArgumentException("Unknown package: " + packageName);
5664            }
5665            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5666            if (ps == null
5667                    || filterAppAccessLPr(ps, callingUid, userId)) {
5668                throw new IllegalArgumentException("Unknown package: " + packageName);
5669            }
5670
5671            final BasePermission bp = mSettings.mPermissions.get(name);
5672            if (bp == null) {
5673                throw new IllegalArgumentException("Unknown permission: " + name);
5674            }
5675
5676            PermissionsState permissionsState = ps.getPermissionsState();
5677
5678            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
5679
5680            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
5681                // Install and runtime permissions are stored in different places,
5682                // so figure out what permission changed and persist the change.
5683                if (permissionsState.getInstallPermissionState(name) != null) {
5684                    scheduleWriteSettingsLocked();
5685                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
5686                        || hadState) {
5687                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5688                }
5689            }
5690        }
5691    }
5692
5693    /**
5694     * Update the permission flags for all packages and runtime permissions of a user in order
5695     * to allow device or profile owner to remove POLICY_FIXED.
5696     */
5697    @Override
5698    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5699        if (!sUserManager.exists(userId)) {
5700            return;
5701        }
5702
5703        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
5704
5705        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5706                true /* requireFullPermission */, true /* checkShell */,
5707                "updatePermissionFlagsForAllApps");
5708
5709        // Only the system can change system fixed flags.
5710        if (getCallingUid() != Process.SYSTEM_UID) {
5711            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5712            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5713        }
5714
5715        synchronized (mPackages) {
5716            boolean changed = false;
5717            final int packageCount = mPackages.size();
5718            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
5719                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
5720                final PackageSetting ps = (PackageSetting) pkg.mExtras;
5721                if (ps == null) {
5722                    continue;
5723                }
5724                PermissionsState permissionsState = ps.getPermissionsState();
5725                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
5726                        userId, flagMask, flagValues);
5727            }
5728            if (changed) {
5729                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5730            }
5731        }
5732    }
5733
5734    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
5735        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
5736                != PackageManager.PERMISSION_GRANTED
5737            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
5738                != PackageManager.PERMISSION_GRANTED) {
5739            throw new SecurityException(message + " requires "
5740                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
5741                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
5742        }
5743    }
5744
5745    @Override
5746    public boolean shouldShowRequestPermissionRationale(String permissionName,
5747            String packageName, int userId) {
5748        if (UserHandle.getCallingUserId() != userId) {
5749            mContext.enforceCallingPermission(
5750                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5751                    "canShowRequestPermissionRationale for user " + userId);
5752        }
5753
5754        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5755        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5756            return false;
5757        }
5758
5759        if (checkPermission(permissionName, packageName, userId)
5760                == PackageManager.PERMISSION_GRANTED) {
5761            return false;
5762        }
5763
5764        final int flags;
5765
5766        final long identity = Binder.clearCallingIdentity();
5767        try {
5768            flags = getPermissionFlags(permissionName,
5769                    packageName, userId);
5770        } finally {
5771            Binder.restoreCallingIdentity(identity);
5772        }
5773
5774        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5775                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5776                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5777
5778        if ((flags & fixedFlags) != 0) {
5779            return false;
5780        }
5781
5782        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5783    }
5784
5785    @Override
5786    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5787        mContext.enforceCallingOrSelfPermission(
5788                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5789                "addOnPermissionsChangeListener");
5790
5791        synchronized (mPackages) {
5792            mOnPermissionChangeListeners.addListenerLocked(listener);
5793        }
5794    }
5795
5796    @Override
5797    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5798        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5799            throw new SecurityException("Instant applications don't have access to this method");
5800        }
5801        synchronized (mPackages) {
5802            mOnPermissionChangeListeners.removeListenerLocked(listener);
5803        }
5804    }
5805
5806    @Override
5807    public boolean isProtectedBroadcast(String actionName) {
5808        // allow instant applications
5809        synchronized (mPackages) {
5810            if (mProtectedBroadcasts.contains(actionName)) {
5811                return true;
5812            } else if (actionName != null) {
5813                // TODO: remove these terrible hacks
5814                if (actionName.startsWith("android.net.netmon.lingerExpired")
5815                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5816                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5817                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5818                    return true;
5819                }
5820            }
5821        }
5822        return false;
5823    }
5824
5825    @Override
5826    public int checkSignatures(String pkg1, String pkg2) {
5827        synchronized (mPackages) {
5828            final PackageParser.Package p1 = mPackages.get(pkg1);
5829            final PackageParser.Package p2 = mPackages.get(pkg2);
5830            if (p1 == null || p1.mExtras == null
5831                    || p2 == null || p2.mExtras == null) {
5832                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5833            }
5834            final int callingUid = Binder.getCallingUid();
5835            final int callingUserId = UserHandle.getUserId(callingUid);
5836            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
5837            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
5838            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
5839                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
5840                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5841            }
5842            return compareSignatures(p1.mSignatures, p2.mSignatures);
5843        }
5844    }
5845
5846    @Override
5847    public int checkUidSignatures(int uid1, int uid2) {
5848        final int callingUid = Binder.getCallingUid();
5849        final int callingUserId = UserHandle.getUserId(callingUid);
5850        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5851        // Map to base uids.
5852        uid1 = UserHandle.getAppId(uid1);
5853        uid2 = UserHandle.getAppId(uid2);
5854        // reader
5855        synchronized (mPackages) {
5856            Signature[] s1;
5857            Signature[] s2;
5858            Object obj = mSettings.getUserIdLPr(uid1);
5859            if (obj != null) {
5860                if (obj instanceof SharedUserSetting) {
5861                    if (isCallerInstantApp) {
5862                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5863                    }
5864                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
5865                } else if (obj instanceof PackageSetting) {
5866                    final PackageSetting ps = (PackageSetting) obj;
5867                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5868                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5869                    }
5870                    s1 = ps.signatures.mSignatures;
5871                } else {
5872                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5873                }
5874            } else {
5875                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5876            }
5877            obj = mSettings.getUserIdLPr(uid2);
5878            if (obj != null) {
5879                if (obj instanceof SharedUserSetting) {
5880                    if (isCallerInstantApp) {
5881                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5882                    }
5883                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
5884                } else if (obj instanceof PackageSetting) {
5885                    final PackageSetting ps = (PackageSetting) obj;
5886                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5887                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5888                    }
5889                    s2 = ps.signatures.mSignatures;
5890                } else {
5891                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5892                }
5893            } else {
5894                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5895            }
5896            return compareSignatures(s1, s2);
5897        }
5898    }
5899
5900    /**
5901     * This method should typically only be used when granting or revoking
5902     * permissions, since the app may immediately restart after this call.
5903     * <p>
5904     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5905     * guard your work against the app being relaunched.
5906     */
5907    private void killUid(int appId, int userId, String reason) {
5908        final long identity = Binder.clearCallingIdentity();
5909        try {
5910            IActivityManager am = ActivityManager.getService();
5911            if (am != null) {
5912                try {
5913                    am.killUid(appId, userId, reason);
5914                } catch (RemoteException e) {
5915                    /* ignore - same process */
5916                }
5917            }
5918        } finally {
5919            Binder.restoreCallingIdentity(identity);
5920        }
5921    }
5922
5923    /**
5924     * Compares two sets of signatures. Returns:
5925     * <br />
5926     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
5927     * <br />
5928     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
5929     * <br />
5930     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
5931     * <br />
5932     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
5933     * <br />
5934     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
5935     */
5936    static int compareSignatures(Signature[] s1, Signature[] s2) {
5937        if (s1 == null) {
5938            return s2 == null
5939                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
5940                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
5941        }
5942
5943        if (s2 == null) {
5944            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
5945        }
5946
5947        if (s1.length != s2.length) {
5948            return PackageManager.SIGNATURE_NO_MATCH;
5949        }
5950
5951        // Since both signature sets are of size 1, we can compare without HashSets.
5952        if (s1.length == 1) {
5953            return s1[0].equals(s2[0]) ?
5954                    PackageManager.SIGNATURE_MATCH :
5955                    PackageManager.SIGNATURE_NO_MATCH;
5956        }
5957
5958        ArraySet<Signature> set1 = new ArraySet<Signature>();
5959        for (Signature sig : s1) {
5960            set1.add(sig);
5961        }
5962        ArraySet<Signature> set2 = new ArraySet<Signature>();
5963        for (Signature sig : s2) {
5964            set2.add(sig);
5965        }
5966        // Make sure s2 contains all signatures in s1.
5967        if (set1.equals(set2)) {
5968            return PackageManager.SIGNATURE_MATCH;
5969        }
5970        return PackageManager.SIGNATURE_NO_MATCH;
5971    }
5972
5973    /**
5974     * If the database version for this type of package (internal storage or
5975     * external storage) is less than the version where package signatures
5976     * were updated, return true.
5977     */
5978    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5979        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5980        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5981    }
5982
5983    /**
5984     * Used for backward compatibility to make sure any packages with
5985     * certificate chains get upgraded to the new style. {@code existingSigs}
5986     * will be in the old format (since they were stored on disk from before the
5987     * system upgrade) and {@code scannedSigs} will be in the newer format.
5988     */
5989    private int compareSignaturesCompat(PackageSignatures existingSigs,
5990            PackageParser.Package scannedPkg) {
5991        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
5992            return PackageManager.SIGNATURE_NO_MATCH;
5993        }
5994
5995        ArraySet<Signature> existingSet = new ArraySet<Signature>();
5996        for (Signature sig : existingSigs.mSignatures) {
5997            existingSet.add(sig);
5998        }
5999        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
6000        for (Signature sig : scannedPkg.mSignatures) {
6001            try {
6002                Signature[] chainSignatures = sig.getChainSignatures();
6003                for (Signature chainSig : chainSignatures) {
6004                    scannedCompatSet.add(chainSig);
6005                }
6006            } catch (CertificateEncodingException e) {
6007                scannedCompatSet.add(sig);
6008            }
6009        }
6010        /*
6011         * Make sure the expanded scanned set contains all signatures in the
6012         * existing one.
6013         */
6014        if (scannedCompatSet.equals(existingSet)) {
6015            // Migrate the old signatures to the new scheme.
6016            existingSigs.assignSignatures(scannedPkg.mSignatures);
6017            // The new KeySets will be re-added later in the scanning process.
6018            synchronized (mPackages) {
6019                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
6020            }
6021            return PackageManager.SIGNATURE_MATCH;
6022        }
6023        return PackageManager.SIGNATURE_NO_MATCH;
6024    }
6025
6026    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6027        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6028        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
6029    }
6030
6031    private int compareSignaturesRecover(PackageSignatures existingSigs,
6032            PackageParser.Package scannedPkg) {
6033        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
6034            return PackageManager.SIGNATURE_NO_MATCH;
6035        }
6036
6037        String msg = null;
6038        try {
6039            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
6040                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
6041                        + scannedPkg.packageName);
6042                return PackageManager.SIGNATURE_MATCH;
6043            }
6044        } catch (CertificateException e) {
6045            msg = e.getMessage();
6046        }
6047
6048        logCriticalInfo(Log.INFO,
6049                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
6050        return PackageManager.SIGNATURE_NO_MATCH;
6051    }
6052
6053    @Override
6054    public List<String> getAllPackages() {
6055        final int callingUid = Binder.getCallingUid();
6056        final int callingUserId = UserHandle.getUserId(callingUid);
6057        synchronized (mPackages) {
6058            if (canViewInstantApps(callingUid, callingUserId)) {
6059                return new ArrayList<String>(mPackages.keySet());
6060            }
6061            final String instantAppPkgName = getInstantAppPackageName(callingUid);
6062            final List<String> result = new ArrayList<>();
6063            if (instantAppPkgName != null) {
6064                // caller is an instant application; filter unexposed applications
6065                for (PackageParser.Package pkg : mPackages.values()) {
6066                    if (!pkg.visibleToInstantApps) {
6067                        continue;
6068                    }
6069                    result.add(pkg.packageName);
6070                }
6071            } else {
6072                // caller is a normal application; filter instant applications
6073                for (PackageParser.Package pkg : mPackages.values()) {
6074                    final PackageSetting ps =
6075                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
6076                    if (ps != null
6077                            && ps.getInstantApp(callingUserId)
6078                            && !mInstantAppRegistry.isInstantAccessGranted(
6079                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
6080                        continue;
6081                    }
6082                    result.add(pkg.packageName);
6083                }
6084            }
6085            return result;
6086        }
6087    }
6088
6089    @Override
6090    public String[] getPackagesForUid(int uid) {
6091        final int callingUid = Binder.getCallingUid();
6092        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
6093        final int userId = UserHandle.getUserId(uid);
6094        uid = UserHandle.getAppId(uid);
6095        // reader
6096        synchronized (mPackages) {
6097            Object obj = mSettings.getUserIdLPr(uid);
6098            if (obj instanceof SharedUserSetting) {
6099                if (isCallerInstantApp) {
6100                    return null;
6101                }
6102                final SharedUserSetting sus = (SharedUserSetting) obj;
6103                final int N = sus.packages.size();
6104                String[] res = new String[N];
6105                final Iterator<PackageSetting> it = sus.packages.iterator();
6106                int i = 0;
6107                while (it.hasNext()) {
6108                    PackageSetting ps = it.next();
6109                    if (ps.getInstalled(userId)) {
6110                        res[i++] = ps.name;
6111                    } else {
6112                        res = ArrayUtils.removeElement(String.class, res, res[i]);
6113                    }
6114                }
6115                return res;
6116            } else if (obj instanceof PackageSetting) {
6117                final PackageSetting ps = (PackageSetting) obj;
6118                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
6119                    return new String[]{ps.name};
6120                }
6121            }
6122        }
6123        return null;
6124    }
6125
6126    @Override
6127    public String getNameForUid(int uid) {
6128        final int callingUid = Binder.getCallingUid();
6129        if (getInstantAppPackageName(callingUid) != null) {
6130            return null;
6131        }
6132        synchronized (mPackages) {
6133            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6134            if (obj instanceof SharedUserSetting) {
6135                final SharedUserSetting sus = (SharedUserSetting) obj;
6136                return sus.name + ":" + sus.userId;
6137            } else if (obj instanceof PackageSetting) {
6138                final PackageSetting ps = (PackageSetting) obj;
6139                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6140                    return null;
6141                }
6142                return ps.name;
6143            }
6144        }
6145        return null;
6146    }
6147
6148    @Override
6149    public int getUidForSharedUser(String sharedUserName) {
6150        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6151            return -1;
6152        }
6153        if (sharedUserName == null) {
6154            return -1;
6155        }
6156        // reader
6157        synchronized (mPackages) {
6158            SharedUserSetting suid;
6159            try {
6160                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
6161                if (suid != null) {
6162                    return suid.userId;
6163                }
6164            } catch (PackageManagerException ignore) {
6165                // can't happen, but, still need to catch it
6166            }
6167            return -1;
6168        }
6169    }
6170
6171    @Override
6172    public int getFlagsForUid(int uid) {
6173        final int callingUid = Binder.getCallingUid();
6174        if (getInstantAppPackageName(callingUid) != null) {
6175            return 0;
6176        }
6177        synchronized (mPackages) {
6178            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6179            if (obj instanceof SharedUserSetting) {
6180                final SharedUserSetting sus = (SharedUserSetting) obj;
6181                return sus.pkgFlags;
6182            } else if (obj instanceof PackageSetting) {
6183                final PackageSetting ps = (PackageSetting) obj;
6184                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6185                    return 0;
6186                }
6187                return ps.pkgFlags;
6188            }
6189        }
6190        return 0;
6191    }
6192
6193    @Override
6194    public int getPrivateFlagsForUid(int uid) {
6195        final int callingUid = Binder.getCallingUid();
6196        if (getInstantAppPackageName(callingUid) != null) {
6197            return 0;
6198        }
6199        synchronized (mPackages) {
6200            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6201            if (obj instanceof SharedUserSetting) {
6202                final SharedUserSetting sus = (SharedUserSetting) obj;
6203                return sus.pkgPrivateFlags;
6204            } else if (obj instanceof PackageSetting) {
6205                final PackageSetting ps = (PackageSetting) obj;
6206                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6207                    return 0;
6208                }
6209                return ps.pkgPrivateFlags;
6210            }
6211        }
6212        return 0;
6213    }
6214
6215    @Override
6216    public boolean isUidPrivileged(int uid) {
6217        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6218            return false;
6219        }
6220        uid = UserHandle.getAppId(uid);
6221        // reader
6222        synchronized (mPackages) {
6223            Object obj = mSettings.getUserIdLPr(uid);
6224            if (obj instanceof SharedUserSetting) {
6225                final SharedUserSetting sus = (SharedUserSetting) obj;
6226                final Iterator<PackageSetting> it = sus.packages.iterator();
6227                while (it.hasNext()) {
6228                    if (it.next().isPrivileged()) {
6229                        return true;
6230                    }
6231                }
6232            } else if (obj instanceof PackageSetting) {
6233                final PackageSetting ps = (PackageSetting) obj;
6234                return ps.isPrivileged();
6235            }
6236        }
6237        return false;
6238    }
6239
6240    @Override
6241    public String[] getAppOpPermissionPackages(String permissionName) {
6242        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6243            return null;
6244        }
6245        synchronized (mPackages) {
6246            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
6247            if (pkgs == null) {
6248                return null;
6249            }
6250            return pkgs.toArray(new String[pkgs.size()]);
6251        }
6252    }
6253
6254    @Override
6255    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
6256            int flags, int userId) {
6257        return resolveIntentInternal(
6258                intent, resolvedType, flags, userId, false /*includeInstantApps*/);
6259    }
6260
6261    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
6262            int flags, int userId, boolean resolveForStart) {
6263        try {
6264            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
6265
6266            if (!sUserManager.exists(userId)) return null;
6267            final int callingUid = Binder.getCallingUid();
6268            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
6269            enforceCrossUserPermission(callingUid, userId,
6270                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
6271
6272            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6273            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
6274                    flags, callingUid, userId, resolveForStart);
6275            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6276
6277            final ResolveInfo bestChoice =
6278                    chooseBestActivity(intent, resolvedType, flags, query, userId);
6279            return bestChoice;
6280        } finally {
6281            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6282        }
6283    }
6284
6285    @Override
6286    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
6287        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
6288            throw new SecurityException(
6289                    "findPersistentPreferredActivity can only be run by the system");
6290        }
6291        if (!sUserManager.exists(userId)) {
6292            return null;
6293        }
6294        final int callingUid = Binder.getCallingUid();
6295        intent = updateIntentForResolve(intent);
6296        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
6297        final int flags = updateFlagsForResolve(
6298                0, userId, intent, callingUid, false /*includeInstantApps*/);
6299        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6300                userId);
6301        synchronized (mPackages) {
6302            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
6303                    userId);
6304        }
6305    }
6306
6307    @Override
6308    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
6309            IntentFilter filter, int match, ComponentName activity) {
6310        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6311            return;
6312        }
6313        final int userId = UserHandle.getCallingUserId();
6314        if (DEBUG_PREFERRED) {
6315            Log.v(TAG, "setLastChosenActivity intent=" + intent
6316                + " resolvedType=" + resolvedType
6317                + " flags=" + flags
6318                + " filter=" + filter
6319                + " match=" + match
6320                + " activity=" + activity);
6321            filter.dump(new PrintStreamPrinter(System.out), "    ");
6322        }
6323        intent.setComponent(null);
6324        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6325                userId);
6326        // Find any earlier preferred or last chosen entries and nuke them
6327        findPreferredActivity(intent, resolvedType,
6328                flags, query, 0, false, true, false, userId);
6329        // Add the new activity as the last chosen for this filter
6330        addPreferredActivityInternal(filter, match, null, activity, false, userId,
6331                "Setting last chosen");
6332    }
6333
6334    @Override
6335    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
6336        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6337            return null;
6338        }
6339        final int userId = UserHandle.getCallingUserId();
6340        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
6341        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6342                userId);
6343        return findPreferredActivity(intent, resolvedType, flags, query, 0,
6344                false, false, false, userId);
6345    }
6346
6347    /**
6348     * Returns whether or not instant apps have been disabled remotely.
6349     */
6350    private boolean isEphemeralDisabled() {
6351        return mEphemeralAppsDisabled;
6352    }
6353
6354    private boolean isInstantAppAllowed(
6355            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
6356            boolean skipPackageCheck) {
6357        if (mInstantAppResolverConnection == null) {
6358            return false;
6359        }
6360        if (mInstantAppInstallerActivity == null) {
6361            return false;
6362        }
6363        if (intent.getComponent() != null) {
6364            return false;
6365        }
6366        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
6367            return false;
6368        }
6369        if (!skipPackageCheck && intent.getPackage() != null) {
6370            return false;
6371        }
6372        final boolean isWebUri = hasWebURI(intent);
6373        if (!isWebUri || intent.getData().getHost() == null) {
6374            return false;
6375        }
6376        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
6377        // Or if there's already an ephemeral app installed that handles the action
6378        synchronized (mPackages) {
6379            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
6380            for (int n = 0; n < count; n++) {
6381                final ResolveInfo info = resolvedActivities.get(n);
6382                final String packageName = info.activityInfo.packageName;
6383                final PackageSetting ps = mSettings.mPackages.get(packageName);
6384                if (ps != null) {
6385                    // only check domain verification status if the app is not a browser
6386                    if (!info.handleAllWebDataURI) {
6387                        // Try to get the status from User settings first
6388                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6389                        final int status = (int) (packedStatus >> 32);
6390                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
6391                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6392                            if (DEBUG_EPHEMERAL) {
6393                                Slog.v(TAG, "DENY instant app;"
6394                                    + " pkg: " + packageName + ", status: " + status);
6395                            }
6396                            return false;
6397                        }
6398                    }
6399                    if (ps.getInstantApp(userId)) {
6400                        if (DEBUG_EPHEMERAL) {
6401                            Slog.v(TAG, "DENY instant app installed;"
6402                                    + " pkg: " + packageName);
6403                        }
6404                        return false;
6405                    }
6406                }
6407            }
6408        }
6409        // We've exhausted all ways to deny ephemeral application; let the system look for them.
6410        return true;
6411    }
6412
6413    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
6414            Intent origIntent, String resolvedType, String callingPackage,
6415            Bundle verificationBundle, int userId) {
6416        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
6417                new InstantAppRequest(responseObj, origIntent, resolvedType,
6418                        callingPackage, userId, verificationBundle));
6419        mHandler.sendMessage(msg);
6420    }
6421
6422    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
6423            int flags, List<ResolveInfo> query, int userId) {
6424        if (query != null) {
6425            final int N = query.size();
6426            if (N == 1) {
6427                return query.get(0);
6428            } else if (N > 1) {
6429                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
6430                // If there is more than one activity with the same priority,
6431                // then let the user decide between them.
6432                ResolveInfo r0 = query.get(0);
6433                ResolveInfo r1 = query.get(1);
6434                if (DEBUG_INTENT_MATCHING || debug) {
6435                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
6436                            + r1.activityInfo.name + "=" + r1.priority);
6437                }
6438                // If the first activity has a higher priority, or a different
6439                // default, then it is always desirable to pick it.
6440                if (r0.priority != r1.priority
6441                        || r0.preferredOrder != r1.preferredOrder
6442                        || r0.isDefault != r1.isDefault) {
6443                    return query.get(0);
6444                }
6445                // If we have saved a preference for a preferred activity for
6446                // this Intent, use that.
6447                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
6448                        flags, query, r0.priority, true, false, debug, userId);
6449                if (ri != null) {
6450                    return ri;
6451                }
6452                // If we have an ephemeral app, use it
6453                for (int i = 0; i < N; i++) {
6454                    ri = query.get(i);
6455                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
6456                        final String packageName = ri.activityInfo.packageName;
6457                        final PackageSetting ps = mSettings.mPackages.get(packageName);
6458                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6459                        final int status = (int)(packedStatus >> 32);
6460                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6461                            return ri;
6462                        }
6463                    }
6464                }
6465                ri = new ResolveInfo(mResolveInfo);
6466                ri.activityInfo = new ActivityInfo(ri.activityInfo);
6467                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6468                // If all of the options come from the same package, show the application's
6469                // label and icon instead of the generic resolver's.
6470                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6471                // and then throw away the ResolveInfo itself, meaning that the caller loses
6472                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6473                // a fallback for this case; we only set the target package's resources on
6474                // the ResolveInfo, not the ActivityInfo.
6475                final String intentPackage = intent.getPackage();
6476                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6477                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6478                    ri.resolvePackageName = intentPackage;
6479                    if (userNeedsBadging(userId)) {
6480                        ri.noResourceId = true;
6481                    } else {
6482                        ri.icon = appi.icon;
6483                    }
6484                    ri.iconResourceId = appi.icon;
6485                    ri.labelRes = appi.labelRes;
6486                }
6487                ri.activityInfo.applicationInfo = new ApplicationInfo(
6488                        ri.activityInfo.applicationInfo);
6489                if (userId != 0) {
6490                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6491                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6492                }
6493                // Make sure that the resolver is displayable in car mode
6494                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6495                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6496                return ri;
6497            }
6498        }
6499        return null;
6500    }
6501
6502    /**
6503     * Return true if the given list is not empty and all of its contents have
6504     * an activityInfo with the given package name.
6505     */
6506    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6507        if (ArrayUtils.isEmpty(list)) {
6508            return false;
6509        }
6510        for (int i = 0, N = list.size(); i < N; i++) {
6511            final ResolveInfo ri = list.get(i);
6512            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6513            if (ai == null || !packageName.equals(ai.packageName)) {
6514                return false;
6515            }
6516        }
6517        return true;
6518    }
6519
6520    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6521            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6522        final int N = query.size();
6523        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6524                .get(userId);
6525        // Get the list of persistent preferred activities that handle the intent
6526        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6527        List<PersistentPreferredActivity> pprefs = ppir != null
6528                ? ppir.queryIntent(intent, resolvedType,
6529                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6530                        userId)
6531                : null;
6532        if (pprefs != null && pprefs.size() > 0) {
6533            final int M = pprefs.size();
6534            for (int i=0; i<M; i++) {
6535                final PersistentPreferredActivity ppa = pprefs.get(i);
6536                if (DEBUG_PREFERRED || debug) {
6537                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6538                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6539                            + "\n  component=" + ppa.mComponent);
6540                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6541                }
6542                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6543                        flags | MATCH_DISABLED_COMPONENTS, userId);
6544                if (DEBUG_PREFERRED || debug) {
6545                    Slog.v(TAG, "Found persistent preferred activity:");
6546                    if (ai != null) {
6547                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6548                    } else {
6549                        Slog.v(TAG, "  null");
6550                    }
6551                }
6552                if (ai == null) {
6553                    // This previously registered persistent preferred activity
6554                    // component is no longer known. Ignore it and do NOT remove it.
6555                    continue;
6556                }
6557                for (int j=0; j<N; j++) {
6558                    final ResolveInfo ri = query.get(j);
6559                    if (!ri.activityInfo.applicationInfo.packageName
6560                            .equals(ai.applicationInfo.packageName)) {
6561                        continue;
6562                    }
6563                    if (!ri.activityInfo.name.equals(ai.name)) {
6564                        continue;
6565                    }
6566                    //  Found a persistent preference that can handle the intent.
6567                    if (DEBUG_PREFERRED || debug) {
6568                        Slog.v(TAG, "Returning persistent preferred activity: " +
6569                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6570                    }
6571                    return ri;
6572                }
6573            }
6574        }
6575        return null;
6576    }
6577
6578    // TODO: handle preferred activities missing while user has amnesia
6579    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6580            List<ResolveInfo> query, int priority, boolean always,
6581            boolean removeMatches, boolean debug, int userId) {
6582        if (!sUserManager.exists(userId)) return null;
6583        final int callingUid = Binder.getCallingUid();
6584        flags = updateFlagsForResolve(
6585                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6586        intent = updateIntentForResolve(intent);
6587        // writer
6588        synchronized (mPackages) {
6589            // Try to find a matching persistent preferred activity.
6590            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6591                    debug, userId);
6592
6593            // If a persistent preferred activity matched, use it.
6594            if (pri != null) {
6595                return pri;
6596            }
6597
6598            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6599            // Get the list of preferred activities that handle the intent
6600            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6601            List<PreferredActivity> prefs = pir != null
6602                    ? pir.queryIntent(intent, resolvedType,
6603                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6604                            userId)
6605                    : null;
6606            if (prefs != null && prefs.size() > 0) {
6607                boolean changed = false;
6608                try {
6609                    // First figure out how good the original match set is.
6610                    // We will only allow preferred activities that came
6611                    // from the same match quality.
6612                    int match = 0;
6613
6614                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6615
6616                    final int N = query.size();
6617                    for (int j=0; j<N; j++) {
6618                        final ResolveInfo ri = query.get(j);
6619                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6620                                + ": 0x" + Integer.toHexString(match));
6621                        if (ri.match > match) {
6622                            match = ri.match;
6623                        }
6624                    }
6625
6626                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6627                            + Integer.toHexString(match));
6628
6629                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6630                    final int M = prefs.size();
6631                    for (int i=0; i<M; i++) {
6632                        final PreferredActivity pa = prefs.get(i);
6633                        if (DEBUG_PREFERRED || debug) {
6634                            Slog.v(TAG, "Checking PreferredActivity ds="
6635                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6636                                    + "\n  component=" + pa.mPref.mComponent);
6637                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6638                        }
6639                        if (pa.mPref.mMatch != match) {
6640                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6641                                    + Integer.toHexString(pa.mPref.mMatch));
6642                            continue;
6643                        }
6644                        // If it's not an "always" type preferred activity and that's what we're
6645                        // looking for, skip it.
6646                        if (always && !pa.mPref.mAlways) {
6647                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6648                            continue;
6649                        }
6650                        final ActivityInfo ai = getActivityInfo(
6651                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6652                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6653                                userId);
6654                        if (DEBUG_PREFERRED || debug) {
6655                            Slog.v(TAG, "Found preferred activity:");
6656                            if (ai != null) {
6657                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6658                            } else {
6659                                Slog.v(TAG, "  null");
6660                            }
6661                        }
6662                        if (ai == null) {
6663                            // This previously registered preferred activity
6664                            // component is no longer known.  Most likely an update
6665                            // to the app was installed and in the new version this
6666                            // component no longer exists.  Clean it up by removing
6667                            // it from the preferred activities list, and skip it.
6668                            Slog.w(TAG, "Removing dangling preferred activity: "
6669                                    + pa.mPref.mComponent);
6670                            pir.removeFilter(pa);
6671                            changed = true;
6672                            continue;
6673                        }
6674                        for (int j=0; j<N; j++) {
6675                            final ResolveInfo ri = query.get(j);
6676                            if (!ri.activityInfo.applicationInfo.packageName
6677                                    .equals(ai.applicationInfo.packageName)) {
6678                                continue;
6679                            }
6680                            if (!ri.activityInfo.name.equals(ai.name)) {
6681                                continue;
6682                            }
6683
6684                            if (removeMatches) {
6685                                pir.removeFilter(pa);
6686                                changed = true;
6687                                if (DEBUG_PREFERRED) {
6688                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6689                                }
6690                                break;
6691                            }
6692
6693                            // Okay we found a previously set preferred or last chosen app.
6694                            // If the result set is different from when this
6695                            // was created, we need to clear it and re-ask the
6696                            // user their preference, if we're looking for an "always" type entry.
6697                            if (always && !pa.mPref.sameSet(query)) {
6698                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
6699                                        + intent + " type " + resolvedType);
6700                                if (DEBUG_PREFERRED) {
6701                                    Slog.v(TAG, "Removing preferred activity since set changed "
6702                                            + pa.mPref.mComponent);
6703                                }
6704                                pir.removeFilter(pa);
6705                                // Re-add the filter as a "last chosen" entry (!always)
6706                                PreferredActivity lastChosen = new PreferredActivity(
6707                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6708                                pir.addFilter(lastChosen);
6709                                changed = true;
6710                                return null;
6711                            }
6712
6713                            // Yay! Either the set matched or we're looking for the last chosen
6714                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6715                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6716                            return ri;
6717                        }
6718                    }
6719                } finally {
6720                    if (changed) {
6721                        if (DEBUG_PREFERRED) {
6722                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6723                        }
6724                        scheduleWritePackageRestrictionsLocked(userId);
6725                    }
6726                }
6727            }
6728        }
6729        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6730        return null;
6731    }
6732
6733    /*
6734     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6735     */
6736    @Override
6737    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6738            int targetUserId) {
6739        mContext.enforceCallingOrSelfPermission(
6740                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6741        List<CrossProfileIntentFilter> matches =
6742                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6743        if (matches != null) {
6744            int size = matches.size();
6745            for (int i = 0; i < size; i++) {
6746                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6747            }
6748        }
6749        if (hasWebURI(intent)) {
6750            // cross-profile app linking works only towards the parent.
6751            final int callingUid = Binder.getCallingUid();
6752            final UserInfo parent = getProfileParent(sourceUserId);
6753            synchronized(mPackages) {
6754                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
6755                        false /*includeInstantApps*/);
6756                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6757                        intent, resolvedType, flags, sourceUserId, parent.id);
6758                return xpDomainInfo != null;
6759            }
6760        }
6761        return false;
6762    }
6763
6764    private UserInfo getProfileParent(int userId) {
6765        final long identity = Binder.clearCallingIdentity();
6766        try {
6767            return sUserManager.getProfileParent(userId);
6768        } finally {
6769            Binder.restoreCallingIdentity(identity);
6770        }
6771    }
6772
6773    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6774            String resolvedType, int userId) {
6775        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6776        if (resolver != null) {
6777            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6778        }
6779        return null;
6780    }
6781
6782    @Override
6783    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6784            String resolvedType, int flags, int userId) {
6785        try {
6786            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6787
6788            return new ParceledListSlice<>(
6789                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6790        } finally {
6791            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6792        }
6793    }
6794
6795    /**
6796     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6797     * instant, returns {@code null}.
6798     */
6799    private String getInstantAppPackageName(int callingUid) {
6800        synchronized (mPackages) {
6801            // If the caller is an isolated app use the owner's uid for the lookup.
6802            if (Process.isIsolated(callingUid)) {
6803                callingUid = mIsolatedOwners.get(callingUid);
6804            }
6805            final int appId = UserHandle.getAppId(callingUid);
6806            final Object obj = mSettings.getUserIdLPr(appId);
6807            if (obj instanceof PackageSetting) {
6808                final PackageSetting ps = (PackageSetting) obj;
6809                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6810                return isInstantApp ? ps.pkg.packageName : null;
6811            }
6812        }
6813        return null;
6814    }
6815
6816    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6817            String resolvedType, int flags, int userId) {
6818        return queryIntentActivitiesInternal(
6819                intent, resolvedType, flags, Binder.getCallingUid(), userId, false);
6820    }
6821
6822    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6823            String resolvedType, int flags, int filterCallingUid, int userId,
6824            boolean resolveForStart) {
6825        if (!sUserManager.exists(userId)) return Collections.emptyList();
6826        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
6827        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6828                false /* requireFullPermission */, false /* checkShell */,
6829                "query intent activities");
6830        final String pkgName = intent.getPackage();
6831        ComponentName comp = intent.getComponent();
6832        if (comp == null) {
6833            if (intent.getSelector() != null) {
6834                intent = intent.getSelector();
6835                comp = intent.getComponent();
6836            }
6837        }
6838
6839        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
6840                comp != null || pkgName != null /*onlyExposedExplicitly*/);
6841        if (comp != null) {
6842            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6843            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6844            if (ai != null) {
6845                // When specifying an explicit component, we prevent the activity from being
6846                // used when either 1) the calling package is normal and the activity is within
6847                // an ephemeral application or 2) the calling package is ephemeral and the
6848                // activity is not visible to ephemeral applications.
6849                final boolean matchInstantApp =
6850                        (flags & PackageManager.MATCH_INSTANT) != 0;
6851                final boolean matchVisibleToInstantAppOnly =
6852                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6853                final boolean matchExplicitlyVisibleOnly =
6854                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
6855                final boolean isCallerInstantApp =
6856                        instantAppPkgName != null;
6857                final boolean isTargetSameInstantApp =
6858                        comp.getPackageName().equals(instantAppPkgName);
6859                final boolean isTargetInstantApp =
6860                        (ai.applicationInfo.privateFlags
6861                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6862                final boolean isTargetVisibleToInstantApp =
6863                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
6864                final boolean isTargetExplicitlyVisibleToInstantApp =
6865                        isTargetVisibleToInstantApp
6866                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
6867                final boolean isTargetHiddenFromInstantApp =
6868                        !isTargetVisibleToInstantApp
6869                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
6870                final boolean blockResolution =
6871                        !isTargetSameInstantApp
6872                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6873                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6874                                        && isTargetHiddenFromInstantApp));
6875                if (!blockResolution) {
6876                    final ResolveInfo ri = new ResolveInfo();
6877                    ri.activityInfo = ai;
6878                    list.add(ri);
6879                }
6880            }
6881            return applyPostResolutionFilter(list, instantAppPkgName);
6882        }
6883
6884        // reader
6885        boolean sortResult = false;
6886        boolean addEphemeral = false;
6887        List<ResolveInfo> result;
6888        final boolean ephemeralDisabled = isEphemeralDisabled();
6889        synchronized (mPackages) {
6890            if (pkgName == null) {
6891                List<CrossProfileIntentFilter> matchingFilters =
6892                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6893                // Check for results that need to skip the current profile.
6894                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6895                        resolvedType, flags, userId);
6896                if (xpResolveInfo != null) {
6897                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6898                    xpResult.add(xpResolveInfo);
6899                    return applyPostResolutionFilter(
6900                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName);
6901                }
6902
6903                // Check for results in the current profile.
6904                result = filterIfNotSystemUser(mActivities.queryIntent(
6905                        intent, resolvedType, flags, userId), userId);
6906                addEphemeral = !ephemeralDisabled
6907                        && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/);
6908                // Check for cross profile results.
6909                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6910                xpResolveInfo = queryCrossProfileIntents(
6911                        matchingFilters, intent, resolvedType, flags, userId,
6912                        hasNonNegativePriorityResult);
6913                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6914                    boolean isVisibleToUser = filterIfNotSystemUser(
6915                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6916                    if (isVisibleToUser) {
6917                        result.add(xpResolveInfo);
6918                        sortResult = true;
6919                    }
6920                }
6921                if (hasWebURI(intent)) {
6922                    CrossProfileDomainInfo xpDomainInfo = null;
6923                    final UserInfo parent = getProfileParent(userId);
6924                    if (parent != null) {
6925                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6926                                flags, userId, parent.id);
6927                    }
6928                    if (xpDomainInfo != null) {
6929                        if (xpResolveInfo != null) {
6930                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6931                            // in the result.
6932                            result.remove(xpResolveInfo);
6933                        }
6934                        if (result.size() == 0 && !addEphemeral) {
6935                            // No result in current profile, but found candidate in parent user.
6936                            // And we are not going to add emphemeral app, so we can return the
6937                            // result straight away.
6938                            result.add(xpDomainInfo.resolveInfo);
6939                            return applyPostResolutionFilter(result, instantAppPkgName);
6940                        }
6941                    } else if (result.size() <= 1 && !addEphemeral) {
6942                        // No result in parent user and <= 1 result in current profile, and we
6943                        // are not going to add emphemeral app, so we can return the result without
6944                        // further processing.
6945                        return applyPostResolutionFilter(result, instantAppPkgName);
6946                    }
6947                    // We have more than one candidate (combining results from current and parent
6948                    // profile), so we need filtering and sorting.
6949                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6950                            intent, flags, result, xpDomainInfo, userId);
6951                    sortResult = true;
6952                }
6953            } else {
6954                final PackageParser.Package pkg = mPackages.get(pkgName);
6955                result = null;
6956                if (pkg != null) {
6957                    result = filterIfNotSystemUser(
6958                            mActivities.queryIntentForPackage(
6959                                    intent, resolvedType, flags, pkg.activities, userId),
6960                            userId);
6961                }
6962                if (result == null || result.size() == 0) {
6963                    // the caller wants to resolve for a particular package; however, there
6964                    // were no installed results, so, try to find an ephemeral result
6965                    addEphemeral = !ephemeralDisabled
6966                            && isInstantAppAllowed(
6967                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
6968                    if (result == null) {
6969                        result = new ArrayList<>();
6970                    }
6971                }
6972            }
6973        }
6974        if (addEphemeral) {
6975            result = maybeAddInstantAppInstaller(result, intent, resolvedType, flags, userId);
6976        }
6977        if (sortResult) {
6978            Collections.sort(result, mResolvePrioritySorter);
6979        }
6980        return applyPostResolutionFilter(result, instantAppPkgName);
6981    }
6982
6983    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
6984            String resolvedType, int flags, int userId) {
6985        // first, check to see if we've got an instant app already installed
6986        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
6987        ResolveInfo localInstantApp = null;
6988        boolean blockResolution = false;
6989        if (!alreadyResolvedLocally) {
6990            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
6991                    flags
6992                        | PackageManager.GET_RESOLVED_FILTER
6993                        | PackageManager.MATCH_INSTANT
6994                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
6995                    userId);
6996            for (int i = instantApps.size() - 1; i >= 0; --i) {
6997                final ResolveInfo info = instantApps.get(i);
6998                final String packageName = info.activityInfo.packageName;
6999                final PackageSetting ps = mSettings.mPackages.get(packageName);
7000                if (ps.getInstantApp(userId)) {
7001                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7002                    final int status = (int)(packedStatus >> 32);
7003                    final int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7004                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7005                        // there's a local instant application installed, but, the user has
7006                        // chosen to never use it; skip resolution and don't acknowledge
7007                        // an instant application is even available
7008                        if (DEBUG_EPHEMERAL) {
7009                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
7010                        }
7011                        blockResolution = true;
7012                        break;
7013                    } else {
7014                        // we have a locally installed instant application; skip resolution
7015                        // but acknowledge there's an instant application available
7016                        if (DEBUG_EPHEMERAL) {
7017                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
7018                        }
7019                        localInstantApp = info;
7020                        break;
7021                    }
7022                }
7023            }
7024        }
7025        // no app installed, let's see if one's available
7026        AuxiliaryResolveInfo auxiliaryResponse = null;
7027        if (!blockResolution) {
7028            if (localInstantApp == null) {
7029                // we don't have an instant app locally, resolve externally
7030                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
7031                final InstantAppRequest requestObject = new InstantAppRequest(
7032                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
7033                        null /*callingPackage*/, userId, null /*verificationBundle*/);
7034                auxiliaryResponse =
7035                        InstantAppResolver.doInstantAppResolutionPhaseOne(
7036                                mContext, mInstantAppResolverConnection, requestObject);
7037                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7038            } else {
7039                // we have an instant application locally, but, we can't admit that since
7040                // callers shouldn't be able to determine prior browsing. create a dummy
7041                // auxiliary response so the downstream code behaves as if there's an
7042                // instant application available externally. when it comes time to start
7043                // the instant application, we'll do the right thing.
7044                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
7045                auxiliaryResponse = new AuxiliaryResolveInfo(
7046                        ai.packageName, null /*splitName*/, ai.versionCode, null /*failureIntent*/);
7047            }
7048        }
7049        if (auxiliaryResponse != null) {
7050            if (DEBUG_EPHEMERAL) {
7051                Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7052            }
7053            final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
7054            final PackageSetting ps =
7055                    mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
7056            if (ps != null) {
7057                ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
7058                        mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
7059                ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
7060                ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
7061                // make sure this resolver is the default
7062                ephemeralInstaller.isDefault = true;
7063                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7064                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7065                // add a non-generic filter
7066                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
7067                ephemeralInstaller.filter.addDataPath(
7068                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
7069                ephemeralInstaller.isInstantAppAvailable = true;
7070                result.add(ephemeralInstaller);
7071            }
7072        }
7073        return result;
7074    }
7075
7076    private static class CrossProfileDomainInfo {
7077        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
7078        ResolveInfo resolveInfo;
7079        /* Best domain verification status of the activities found in the other profile */
7080        int bestDomainVerificationStatus;
7081    }
7082
7083    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
7084            String resolvedType, int flags, int sourceUserId, int parentUserId) {
7085        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
7086                sourceUserId)) {
7087            return null;
7088        }
7089        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7090                resolvedType, flags, parentUserId);
7091
7092        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
7093            return null;
7094        }
7095        CrossProfileDomainInfo result = null;
7096        int size = resultTargetUser.size();
7097        for (int i = 0; i < size; i++) {
7098            ResolveInfo riTargetUser = resultTargetUser.get(i);
7099            // Intent filter verification is only for filters that specify a host. So don't return
7100            // those that handle all web uris.
7101            if (riTargetUser.handleAllWebDataURI) {
7102                continue;
7103            }
7104            String packageName = riTargetUser.activityInfo.packageName;
7105            PackageSetting ps = mSettings.mPackages.get(packageName);
7106            if (ps == null) {
7107                continue;
7108            }
7109            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
7110            int status = (int)(verificationState >> 32);
7111            if (result == null) {
7112                result = new CrossProfileDomainInfo();
7113                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
7114                        sourceUserId, parentUserId);
7115                result.bestDomainVerificationStatus = status;
7116            } else {
7117                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
7118                        result.bestDomainVerificationStatus);
7119            }
7120        }
7121        // Don't consider matches with status NEVER across profiles.
7122        if (result != null && result.bestDomainVerificationStatus
7123                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7124            return null;
7125        }
7126        return result;
7127    }
7128
7129    /**
7130     * Verification statuses are ordered from the worse to the best, except for
7131     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
7132     */
7133    private int bestDomainVerificationStatus(int status1, int status2) {
7134        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7135            return status2;
7136        }
7137        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7138            return status1;
7139        }
7140        return (int) MathUtils.max(status1, status2);
7141    }
7142
7143    private boolean isUserEnabled(int userId) {
7144        long callingId = Binder.clearCallingIdentity();
7145        try {
7146            UserInfo userInfo = sUserManager.getUserInfo(userId);
7147            return userInfo != null && userInfo.isEnabled();
7148        } finally {
7149            Binder.restoreCallingIdentity(callingId);
7150        }
7151    }
7152
7153    /**
7154     * Filter out activities with systemUserOnly flag set, when current user is not System.
7155     *
7156     * @return filtered list
7157     */
7158    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
7159        if (userId == UserHandle.USER_SYSTEM) {
7160            return resolveInfos;
7161        }
7162        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7163            ResolveInfo info = resolveInfos.get(i);
7164            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
7165                resolveInfos.remove(i);
7166            }
7167        }
7168        return resolveInfos;
7169    }
7170
7171    /**
7172     * Filters out ephemeral activities.
7173     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
7174     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
7175     *
7176     * @param resolveInfos The pre-filtered list of resolved activities
7177     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
7178     *          is performed.
7179     * @return A filtered list of resolved activities.
7180     */
7181    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
7182            String ephemeralPkgName) {
7183        // TODO: When adding on-demand split support for non-instant apps, remove this check
7184        // and always apply post filtering
7185        if (ephemeralPkgName == null) {
7186            return resolveInfos;
7187        }
7188        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7189            final ResolveInfo info = resolveInfos.get(i);
7190            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
7191            // allow activities that are defined in the provided package
7192            if (isEphemeralApp && ephemeralPkgName.equals(info.activityInfo.packageName)) {
7193                if (info.activityInfo.splitName != null
7194                        && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
7195                                info.activityInfo.splitName)) {
7196                    // requested activity is defined in a split that hasn't been installed yet.
7197                    // add the installer to the resolve list
7198                    if (DEBUG_EPHEMERAL) {
7199                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7200                    }
7201                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7202                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7203                            info.activityInfo.packageName, info.activityInfo.splitName,
7204                            info.activityInfo.applicationInfo.versionCode, null /*failureIntent*/);
7205                    // make sure this resolver is the default
7206                    installerInfo.isDefault = true;
7207                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7208                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7209                    // add a non-generic filter
7210                    installerInfo.filter = new IntentFilter();
7211                    // load resources from the correct package
7212                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7213                    resolveInfos.set(i, installerInfo);
7214                }
7215                continue;
7216            }
7217            // allow activities that have been explicitly exposed to ephemeral apps
7218            if (!isEphemeralApp
7219                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7220                continue;
7221            }
7222            resolveInfos.remove(i);
7223        }
7224        return resolveInfos;
7225    }
7226
7227    /**
7228     * @param resolveInfos list of resolve infos in descending priority order
7229     * @return if the list contains a resolve info with non-negative priority
7230     */
7231    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
7232        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
7233    }
7234
7235    private static boolean hasWebURI(Intent intent) {
7236        if (intent.getData() == null) {
7237            return false;
7238        }
7239        final String scheme = intent.getScheme();
7240        if (TextUtils.isEmpty(scheme)) {
7241            return false;
7242        }
7243        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
7244    }
7245
7246    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
7247            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
7248            int userId) {
7249        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
7250
7251        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7252            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
7253                    candidates.size());
7254        }
7255
7256        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
7257        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
7258        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
7259        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
7260        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
7261        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
7262
7263        synchronized (mPackages) {
7264            final int count = candidates.size();
7265            // First, try to use linked apps. Partition the candidates into four lists:
7266            // one for the final results, one for the "do not use ever", one for "undefined status"
7267            // and finally one for "browser app type".
7268            for (int n=0; n<count; n++) {
7269                ResolveInfo info = candidates.get(n);
7270                String packageName = info.activityInfo.packageName;
7271                PackageSetting ps = mSettings.mPackages.get(packageName);
7272                if (ps != null) {
7273                    // Add to the special match all list (Browser use case)
7274                    if (info.handleAllWebDataURI) {
7275                        matchAllList.add(info);
7276                        continue;
7277                    }
7278                    // Try to get the status from User settings first
7279                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7280                    int status = (int)(packedStatus >> 32);
7281                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7282                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
7283                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7284                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
7285                                    + " : linkgen=" + linkGeneration);
7286                        }
7287                        // Use link-enabled generation as preferredOrder, i.e.
7288                        // prefer newly-enabled over earlier-enabled.
7289                        info.preferredOrder = linkGeneration;
7290                        alwaysList.add(info);
7291                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7292                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7293                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
7294                        }
7295                        neverList.add(info);
7296                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
7297                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7298                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
7299                        }
7300                        alwaysAskList.add(info);
7301                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
7302                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
7303                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7304                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
7305                        }
7306                        undefinedList.add(info);
7307                    }
7308                }
7309            }
7310
7311            // We'll want to include browser possibilities in a few cases
7312            boolean includeBrowser = false;
7313
7314            // First try to add the "always" resolution(s) for the current user, if any
7315            if (alwaysList.size() > 0) {
7316                result.addAll(alwaysList);
7317            } else {
7318                // Add all undefined apps as we want them to appear in the disambiguation dialog.
7319                result.addAll(undefinedList);
7320                // Maybe add one for the other profile.
7321                if (xpDomainInfo != null && (
7322                        xpDomainInfo.bestDomainVerificationStatus
7323                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
7324                    result.add(xpDomainInfo.resolveInfo);
7325                }
7326                includeBrowser = true;
7327            }
7328
7329            // The presence of any 'always ask' alternatives means we'll also offer browsers.
7330            // If there were 'always' entries their preferred order has been set, so we also
7331            // back that off to make the alternatives equivalent
7332            if (alwaysAskList.size() > 0) {
7333                for (ResolveInfo i : result) {
7334                    i.preferredOrder = 0;
7335                }
7336                result.addAll(alwaysAskList);
7337                includeBrowser = true;
7338            }
7339
7340            if (includeBrowser) {
7341                // Also add browsers (all of them or only the default one)
7342                if (DEBUG_DOMAIN_VERIFICATION) {
7343                    Slog.v(TAG, "   ...including browsers in candidate set");
7344                }
7345                if ((matchFlags & MATCH_ALL) != 0) {
7346                    result.addAll(matchAllList);
7347                } else {
7348                    // Browser/generic handling case.  If there's a default browser, go straight
7349                    // to that (but only if there is no other higher-priority match).
7350                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7351                    int maxMatchPrio = 0;
7352                    ResolveInfo defaultBrowserMatch = null;
7353                    final int numCandidates = matchAllList.size();
7354                    for (int n = 0; n < numCandidates; n++) {
7355                        ResolveInfo info = matchAllList.get(n);
7356                        // track the highest overall match priority...
7357                        if (info.priority > maxMatchPrio) {
7358                            maxMatchPrio = info.priority;
7359                        }
7360                        // ...and the highest-priority default browser match
7361                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7362                            if (defaultBrowserMatch == null
7363                                    || (defaultBrowserMatch.priority < info.priority)) {
7364                                if (debug) {
7365                                    Slog.v(TAG, "Considering default browser match " + info);
7366                                }
7367                                defaultBrowserMatch = info;
7368                            }
7369                        }
7370                    }
7371                    if (defaultBrowserMatch != null
7372                            && defaultBrowserMatch.priority >= maxMatchPrio
7373                            && !TextUtils.isEmpty(defaultBrowserPackageName))
7374                    {
7375                        if (debug) {
7376                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7377                        }
7378                        result.add(defaultBrowserMatch);
7379                    } else {
7380                        result.addAll(matchAllList);
7381                    }
7382                }
7383
7384                // If there is nothing selected, add all candidates and remove the ones that the user
7385                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7386                if (result.size() == 0) {
7387                    result.addAll(candidates);
7388                    result.removeAll(neverList);
7389                }
7390            }
7391        }
7392        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7393            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7394                    result.size());
7395            for (ResolveInfo info : result) {
7396                Slog.v(TAG, "  + " + info.activityInfo);
7397            }
7398        }
7399        return result;
7400    }
7401
7402    // Returns a packed value as a long:
7403    //
7404    // high 'int'-sized word: link status: undefined/ask/never/always.
7405    // low 'int'-sized word: relative priority among 'always' results.
7406    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7407        long result = ps.getDomainVerificationStatusForUser(userId);
7408        // if none available, get the master status
7409        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7410            if (ps.getIntentFilterVerificationInfo() != null) {
7411                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7412            }
7413        }
7414        return result;
7415    }
7416
7417    private ResolveInfo querySkipCurrentProfileIntents(
7418            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7419            int flags, int sourceUserId) {
7420        if (matchingFilters != null) {
7421            int size = matchingFilters.size();
7422            for (int i = 0; i < size; i ++) {
7423                CrossProfileIntentFilter filter = matchingFilters.get(i);
7424                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7425                    // Checking if there are activities in the target user that can handle the
7426                    // intent.
7427                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7428                            resolvedType, flags, sourceUserId);
7429                    if (resolveInfo != null) {
7430                        return resolveInfo;
7431                    }
7432                }
7433            }
7434        }
7435        return null;
7436    }
7437
7438    // Return matching ResolveInfo in target user if any.
7439    private ResolveInfo queryCrossProfileIntents(
7440            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7441            int flags, int sourceUserId, boolean matchInCurrentProfile) {
7442        if (matchingFilters != null) {
7443            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7444            // match the same intent. For performance reasons, it is better not to
7445            // run queryIntent twice for the same userId
7446            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7447            int size = matchingFilters.size();
7448            for (int i = 0; i < size; i++) {
7449                CrossProfileIntentFilter filter = matchingFilters.get(i);
7450                int targetUserId = filter.getTargetUserId();
7451                boolean skipCurrentProfile =
7452                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7453                boolean skipCurrentProfileIfNoMatchFound =
7454                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7455                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7456                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7457                    // Checking if there are activities in the target user that can handle the
7458                    // intent.
7459                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7460                            resolvedType, flags, sourceUserId);
7461                    if (resolveInfo != null) return resolveInfo;
7462                    alreadyTriedUserIds.put(targetUserId, true);
7463                }
7464            }
7465        }
7466        return null;
7467    }
7468
7469    /**
7470     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7471     * will forward the intent to the filter's target user.
7472     * Otherwise, returns null.
7473     */
7474    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7475            String resolvedType, int flags, int sourceUserId) {
7476        int targetUserId = filter.getTargetUserId();
7477        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7478                resolvedType, flags, targetUserId);
7479        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7480            // If all the matches in the target profile are suspended, return null.
7481            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7482                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7483                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7484                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7485                            targetUserId);
7486                }
7487            }
7488        }
7489        return null;
7490    }
7491
7492    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7493            int sourceUserId, int targetUserId) {
7494        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7495        long ident = Binder.clearCallingIdentity();
7496        boolean targetIsProfile;
7497        try {
7498            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7499        } finally {
7500            Binder.restoreCallingIdentity(ident);
7501        }
7502        String className;
7503        if (targetIsProfile) {
7504            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7505        } else {
7506            className = FORWARD_INTENT_TO_PARENT;
7507        }
7508        ComponentName forwardingActivityComponentName = new ComponentName(
7509                mAndroidApplication.packageName, className);
7510        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7511                sourceUserId);
7512        if (!targetIsProfile) {
7513            forwardingActivityInfo.showUserIcon = targetUserId;
7514            forwardingResolveInfo.noResourceId = true;
7515        }
7516        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7517        forwardingResolveInfo.priority = 0;
7518        forwardingResolveInfo.preferredOrder = 0;
7519        forwardingResolveInfo.match = 0;
7520        forwardingResolveInfo.isDefault = true;
7521        forwardingResolveInfo.filter = filter;
7522        forwardingResolveInfo.targetUserId = targetUserId;
7523        return forwardingResolveInfo;
7524    }
7525
7526    @Override
7527    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7528            Intent[] specifics, String[] specificTypes, Intent intent,
7529            String resolvedType, int flags, int userId) {
7530        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7531                specificTypes, intent, resolvedType, flags, userId));
7532    }
7533
7534    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7535            Intent[] specifics, String[] specificTypes, Intent intent,
7536            String resolvedType, int flags, int userId) {
7537        if (!sUserManager.exists(userId)) return Collections.emptyList();
7538        final int callingUid = Binder.getCallingUid();
7539        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7540                false /*includeInstantApps*/);
7541        enforceCrossUserPermission(callingUid, userId,
7542                false /*requireFullPermission*/, false /*checkShell*/,
7543                "query intent activity options");
7544        final String resultsAction = intent.getAction();
7545
7546        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7547                | PackageManager.GET_RESOLVED_FILTER, userId);
7548
7549        if (DEBUG_INTENT_MATCHING) {
7550            Log.v(TAG, "Query " + intent + ": " + results);
7551        }
7552
7553        int specificsPos = 0;
7554        int N;
7555
7556        // todo: note that the algorithm used here is O(N^2).  This
7557        // isn't a problem in our current environment, but if we start running
7558        // into situations where we have more than 5 or 10 matches then this
7559        // should probably be changed to something smarter...
7560
7561        // First we go through and resolve each of the specific items
7562        // that were supplied, taking care of removing any corresponding
7563        // duplicate items in the generic resolve list.
7564        if (specifics != null) {
7565            for (int i=0; i<specifics.length; i++) {
7566                final Intent sintent = specifics[i];
7567                if (sintent == null) {
7568                    continue;
7569                }
7570
7571                if (DEBUG_INTENT_MATCHING) {
7572                    Log.v(TAG, "Specific #" + i + ": " + sintent);
7573                }
7574
7575                String action = sintent.getAction();
7576                if (resultsAction != null && resultsAction.equals(action)) {
7577                    // If this action was explicitly requested, then don't
7578                    // remove things that have it.
7579                    action = null;
7580                }
7581
7582                ResolveInfo ri = null;
7583                ActivityInfo ai = null;
7584
7585                ComponentName comp = sintent.getComponent();
7586                if (comp == null) {
7587                    ri = resolveIntent(
7588                        sintent,
7589                        specificTypes != null ? specificTypes[i] : null,
7590                            flags, userId);
7591                    if (ri == null) {
7592                        continue;
7593                    }
7594                    if (ri == mResolveInfo) {
7595                        // ACK!  Must do something better with this.
7596                    }
7597                    ai = ri.activityInfo;
7598                    comp = new ComponentName(ai.applicationInfo.packageName,
7599                            ai.name);
7600                } else {
7601                    ai = getActivityInfo(comp, flags, userId);
7602                    if (ai == null) {
7603                        continue;
7604                    }
7605                }
7606
7607                // Look for any generic query activities that are duplicates
7608                // of this specific one, and remove them from the results.
7609                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
7610                N = results.size();
7611                int j;
7612                for (j=specificsPos; j<N; j++) {
7613                    ResolveInfo sri = results.get(j);
7614                    if ((sri.activityInfo.name.equals(comp.getClassName())
7615                            && sri.activityInfo.applicationInfo.packageName.equals(
7616                                    comp.getPackageName()))
7617                        || (action != null && sri.filter.matchAction(action))) {
7618                        results.remove(j);
7619                        if (DEBUG_INTENT_MATCHING) Log.v(
7620                            TAG, "Removing duplicate item from " + j
7621                            + " due to specific " + specificsPos);
7622                        if (ri == null) {
7623                            ri = sri;
7624                        }
7625                        j--;
7626                        N--;
7627                    }
7628                }
7629
7630                // Add this specific item to its proper place.
7631                if (ri == null) {
7632                    ri = new ResolveInfo();
7633                    ri.activityInfo = ai;
7634                }
7635                results.add(specificsPos, ri);
7636                ri.specificIndex = i;
7637                specificsPos++;
7638            }
7639        }
7640
7641        // Now we go through the remaining generic results and remove any
7642        // duplicate actions that are found here.
7643        N = results.size();
7644        for (int i=specificsPos; i<N-1; i++) {
7645            final ResolveInfo rii = results.get(i);
7646            if (rii.filter == null) {
7647                continue;
7648            }
7649
7650            // Iterate over all of the actions of this result's intent
7651            // filter...  typically this should be just one.
7652            final Iterator<String> it = rii.filter.actionsIterator();
7653            if (it == null) {
7654                continue;
7655            }
7656            while (it.hasNext()) {
7657                final String action = it.next();
7658                if (resultsAction != null && resultsAction.equals(action)) {
7659                    // If this action was explicitly requested, then don't
7660                    // remove things that have it.
7661                    continue;
7662                }
7663                for (int j=i+1; j<N; j++) {
7664                    final ResolveInfo rij = results.get(j);
7665                    if (rij.filter != null && rij.filter.hasAction(action)) {
7666                        results.remove(j);
7667                        if (DEBUG_INTENT_MATCHING) Log.v(
7668                            TAG, "Removing duplicate item from " + j
7669                            + " due to action " + action + " at " + i);
7670                        j--;
7671                        N--;
7672                    }
7673                }
7674            }
7675
7676            // If the caller didn't request filter information, drop it now
7677            // so we don't have to marshall/unmarshall it.
7678            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7679                rii.filter = null;
7680            }
7681        }
7682
7683        // Filter out the caller activity if so requested.
7684        if (caller != null) {
7685            N = results.size();
7686            for (int i=0; i<N; i++) {
7687                ActivityInfo ainfo = results.get(i).activityInfo;
7688                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
7689                        && caller.getClassName().equals(ainfo.name)) {
7690                    results.remove(i);
7691                    break;
7692                }
7693            }
7694        }
7695
7696        // If the caller didn't request filter information,
7697        // drop them now so we don't have to
7698        // marshall/unmarshall it.
7699        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7700            N = results.size();
7701            for (int i=0; i<N; i++) {
7702                results.get(i).filter = null;
7703            }
7704        }
7705
7706        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
7707        return results;
7708    }
7709
7710    @Override
7711    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
7712            String resolvedType, int flags, int userId) {
7713        return new ParceledListSlice<>(
7714                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
7715    }
7716
7717    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
7718            String resolvedType, int flags, int userId) {
7719        if (!sUserManager.exists(userId)) return Collections.emptyList();
7720        final int callingUid = Binder.getCallingUid();
7721        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7722        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7723                false /*includeInstantApps*/);
7724        ComponentName comp = intent.getComponent();
7725        if (comp == null) {
7726            if (intent.getSelector() != null) {
7727                intent = intent.getSelector();
7728                comp = intent.getComponent();
7729            }
7730        }
7731        if (comp != null) {
7732            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7733            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
7734            if (ai != null) {
7735                // When specifying an explicit component, we prevent the activity from being
7736                // used when either 1) the calling package is normal and the activity is within
7737                // an instant application or 2) the calling package is ephemeral and the
7738                // activity is not visible to instant applications.
7739                final boolean matchInstantApp =
7740                        (flags & PackageManager.MATCH_INSTANT) != 0;
7741                final boolean matchVisibleToInstantAppOnly =
7742                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7743                final boolean matchExplicitlyVisibleOnly =
7744                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7745                final boolean isCallerInstantApp =
7746                        instantAppPkgName != null;
7747                final boolean isTargetSameInstantApp =
7748                        comp.getPackageName().equals(instantAppPkgName);
7749                final boolean isTargetInstantApp =
7750                        (ai.applicationInfo.privateFlags
7751                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7752                final boolean isTargetVisibleToInstantApp =
7753                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7754                final boolean isTargetExplicitlyVisibleToInstantApp =
7755                        isTargetVisibleToInstantApp
7756                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7757                final boolean isTargetHiddenFromInstantApp =
7758                        !isTargetVisibleToInstantApp
7759                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7760                final boolean blockResolution =
7761                        !isTargetSameInstantApp
7762                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7763                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7764                                        && isTargetHiddenFromInstantApp));
7765                if (!blockResolution) {
7766                    ResolveInfo ri = new ResolveInfo();
7767                    ri.activityInfo = ai;
7768                    list.add(ri);
7769                }
7770            }
7771            return applyPostResolutionFilter(list, instantAppPkgName);
7772        }
7773
7774        // reader
7775        synchronized (mPackages) {
7776            String pkgName = intent.getPackage();
7777            if (pkgName == null) {
7778                final List<ResolveInfo> result =
7779                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
7780                return applyPostResolutionFilter(result, instantAppPkgName);
7781            }
7782            final PackageParser.Package pkg = mPackages.get(pkgName);
7783            if (pkg != null) {
7784                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
7785                        intent, resolvedType, flags, pkg.receivers, userId);
7786                return applyPostResolutionFilter(result, instantAppPkgName);
7787            }
7788            return Collections.emptyList();
7789        }
7790    }
7791
7792    @Override
7793    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7794        final int callingUid = Binder.getCallingUid();
7795        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
7796    }
7797
7798    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
7799            int userId, int callingUid) {
7800        if (!sUserManager.exists(userId)) return null;
7801        flags = updateFlagsForResolve(
7802                flags, userId, intent, callingUid, false /*includeInstantApps*/);
7803        List<ResolveInfo> query = queryIntentServicesInternal(
7804                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
7805        if (query != null) {
7806            if (query.size() >= 1) {
7807                // If there is more than one service with the same priority,
7808                // just arbitrarily pick the first one.
7809                return query.get(0);
7810            }
7811        }
7812        return null;
7813    }
7814
7815    @Override
7816    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7817            String resolvedType, int flags, int userId) {
7818        final int callingUid = Binder.getCallingUid();
7819        return new ParceledListSlice<>(queryIntentServicesInternal(
7820                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
7821    }
7822
7823    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7824            String resolvedType, int flags, int userId, int callingUid,
7825            boolean includeInstantApps) {
7826        if (!sUserManager.exists(userId)) return Collections.emptyList();
7827        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7828        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7829        ComponentName comp = intent.getComponent();
7830        if (comp == null) {
7831            if (intent.getSelector() != null) {
7832                intent = intent.getSelector();
7833                comp = intent.getComponent();
7834            }
7835        }
7836        if (comp != null) {
7837            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7838            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7839            if (si != null) {
7840                // When specifying an explicit component, we prevent the service from being
7841                // used when either 1) the service is in an instant application and the
7842                // caller is not the same instant application or 2) the calling package is
7843                // ephemeral and the activity is not visible to ephemeral applications.
7844                final boolean matchInstantApp =
7845                        (flags & PackageManager.MATCH_INSTANT) != 0;
7846                final boolean matchVisibleToInstantAppOnly =
7847                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7848                final boolean isCallerInstantApp =
7849                        instantAppPkgName != null;
7850                final boolean isTargetSameInstantApp =
7851                        comp.getPackageName().equals(instantAppPkgName);
7852                final boolean isTargetInstantApp =
7853                        (si.applicationInfo.privateFlags
7854                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7855                final boolean isTargetHiddenFromInstantApp =
7856                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7857                final boolean blockResolution =
7858                        !isTargetSameInstantApp
7859                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7860                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7861                                        && isTargetHiddenFromInstantApp));
7862                if (!blockResolution) {
7863                    final ResolveInfo ri = new ResolveInfo();
7864                    ri.serviceInfo = si;
7865                    list.add(ri);
7866                }
7867            }
7868            return list;
7869        }
7870
7871        // reader
7872        synchronized (mPackages) {
7873            String pkgName = intent.getPackage();
7874            if (pkgName == null) {
7875                return applyPostServiceResolutionFilter(
7876                        mServices.queryIntent(intent, resolvedType, flags, userId),
7877                        instantAppPkgName);
7878            }
7879            final PackageParser.Package pkg = mPackages.get(pkgName);
7880            if (pkg != null) {
7881                return applyPostServiceResolutionFilter(
7882                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7883                                userId),
7884                        instantAppPkgName);
7885            }
7886            return Collections.emptyList();
7887        }
7888    }
7889
7890    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
7891            String instantAppPkgName) {
7892        // TODO: When adding on-demand split support for non-instant apps, remove this check
7893        // and always apply post filtering
7894        if (instantAppPkgName == null) {
7895            return resolveInfos;
7896        }
7897        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7898            final ResolveInfo info = resolveInfos.get(i);
7899            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
7900            // allow services that are defined in the provided package
7901            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
7902                if (info.serviceInfo.splitName != null
7903                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
7904                                info.serviceInfo.splitName)) {
7905                    // requested service is defined in a split that hasn't been installed yet.
7906                    // add the installer to the resolve list
7907                    if (DEBUG_EPHEMERAL) {
7908                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7909                    }
7910                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7911                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7912                            info.serviceInfo.packageName, info.serviceInfo.splitName,
7913                            info.serviceInfo.applicationInfo.versionCode, null /*failureIntent*/);
7914                    // make sure this resolver is the default
7915                    installerInfo.isDefault = true;
7916                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7917                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7918                    // add a non-generic filter
7919                    installerInfo.filter = new IntentFilter();
7920                    // load resources from the correct package
7921                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7922                    resolveInfos.set(i, installerInfo);
7923                }
7924                continue;
7925            }
7926            // allow services that have been explicitly exposed to ephemeral apps
7927            if (!isEphemeralApp
7928                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7929                continue;
7930            }
7931            resolveInfos.remove(i);
7932        }
7933        return resolveInfos;
7934    }
7935
7936    @Override
7937    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7938            String resolvedType, int flags, int userId) {
7939        return new ParceledListSlice<>(
7940                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7941    }
7942
7943    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7944            Intent intent, String resolvedType, int flags, int userId) {
7945        if (!sUserManager.exists(userId)) return Collections.emptyList();
7946        final int callingUid = Binder.getCallingUid();
7947        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7948        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7949                false /*includeInstantApps*/);
7950        ComponentName comp = intent.getComponent();
7951        if (comp == null) {
7952            if (intent.getSelector() != null) {
7953                intent = intent.getSelector();
7954                comp = intent.getComponent();
7955            }
7956        }
7957        if (comp != null) {
7958            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7959            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
7960            if (pi != null) {
7961                // When specifying an explicit component, we prevent the provider from being
7962                // used when either 1) the provider is in an instant application and the
7963                // caller is not the same instant application or 2) the calling package is an
7964                // instant application and the provider is not visible to instant applications.
7965                final boolean matchInstantApp =
7966                        (flags & PackageManager.MATCH_INSTANT) != 0;
7967                final boolean matchVisibleToInstantAppOnly =
7968                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7969                final boolean isCallerInstantApp =
7970                        instantAppPkgName != null;
7971                final boolean isTargetSameInstantApp =
7972                        comp.getPackageName().equals(instantAppPkgName);
7973                final boolean isTargetInstantApp =
7974                        (pi.applicationInfo.privateFlags
7975                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7976                final boolean isTargetHiddenFromInstantApp =
7977                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7978                final boolean blockResolution =
7979                        !isTargetSameInstantApp
7980                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7981                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7982                                        && isTargetHiddenFromInstantApp));
7983                if (!blockResolution) {
7984                    final ResolveInfo ri = new ResolveInfo();
7985                    ri.providerInfo = pi;
7986                    list.add(ri);
7987                }
7988            }
7989            return list;
7990        }
7991
7992        // reader
7993        synchronized (mPackages) {
7994            String pkgName = intent.getPackage();
7995            if (pkgName == null) {
7996                return applyPostContentProviderResolutionFilter(
7997                        mProviders.queryIntent(intent, resolvedType, flags, userId),
7998                        instantAppPkgName);
7999            }
8000            final PackageParser.Package pkg = mPackages.get(pkgName);
8001            if (pkg != null) {
8002                return applyPostContentProviderResolutionFilter(
8003                        mProviders.queryIntentForPackage(
8004                        intent, resolvedType, flags, pkg.providers, userId),
8005                        instantAppPkgName);
8006            }
8007            return Collections.emptyList();
8008        }
8009    }
8010
8011    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
8012            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
8013        // TODO: When adding on-demand split support for non-instant applications, remove
8014        // this check and always apply post filtering
8015        if (instantAppPkgName == null) {
8016            return resolveInfos;
8017        }
8018        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
8019            final ResolveInfo info = resolveInfos.get(i);
8020            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
8021            // allow providers that are defined in the provided package
8022            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
8023                if (info.providerInfo.splitName != null
8024                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
8025                                info.providerInfo.splitName)) {
8026                    // requested provider is defined in a split that hasn't been installed yet.
8027                    // add the installer to the resolve list
8028                    if (DEBUG_EPHEMERAL) {
8029                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
8030                    }
8031                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
8032                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
8033                            info.providerInfo.packageName, info.providerInfo.splitName,
8034                            info.providerInfo.applicationInfo.versionCode, null /*failureIntent*/);
8035                    // make sure this resolver is the default
8036                    installerInfo.isDefault = true;
8037                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
8038                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
8039                    // add a non-generic filter
8040                    installerInfo.filter = new IntentFilter();
8041                    // load resources from the correct package
8042                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
8043                    resolveInfos.set(i, installerInfo);
8044                }
8045                continue;
8046            }
8047            // allow providers that have been explicitly exposed to instant applications
8048            if (!isEphemeralApp
8049                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
8050                continue;
8051            }
8052            resolveInfos.remove(i);
8053        }
8054        return resolveInfos;
8055    }
8056
8057    @Override
8058    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
8059        final int callingUid = Binder.getCallingUid();
8060        if (getInstantAppPackageName(callingUid) != null) {
8061            return ParceledListSlice.emptyList();
8062        }
8063        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8064        flags = updateFlagsForPackage(flags, userId, null);
8065        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8066        enforceCrossUserPermission(callingUid, userId,
8067                true /* requireFullPermission */, false /* checkShell */,
8068                "get installed packages");
8069
8070        // writer
8071        synchronized (mPackages) {
8072            ArrayList<PackageInfo> list;
8073            if (listUninstalled) {
8074                list = new ArrayList<>(mSettings.mPackages.size());
8075                for (PackageSetting ps : mSettings.mPackages.values()) {
8076                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8077                        continue;
8078                    }
8079                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8080                        return null;
8081                    }
8082                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8083                    if (pi != null) {
8084                        list.add(pi);
8085                    }
8086                }
8087            } else {
8088                list = new ArrayList<>(mPackages.size());
8089                for (PackageParser.Package p : mPackages.values()) {
8090                    final PackageSetting ps = (PackageSetting) p.mExtras;
8091                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8092                        continue;
8093                    }
8094                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8095                        return null;
8096                    }
8097                    final PackageInfo pi = generatePackageInfo((PackageSetting)
8098                            p.mExtras, flags, userId);
8099                    if (pi != null) {
8100                        list.add(pi);
8101                    }
8102                }
8103            }
8104
8105            return new ParceledListSlice<>(list);
8106        }
8107    }
8108
8109    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
8110            String[] permissions, boolean[] tmp, int flags, int userId) {
8111        int numMatch = 0;
8112        final PermissionsState permissionsState = ps.getPermissionsState();
8113        for (int i=0; i<permissions.length; i++) {
8114            final String permission = permissions[i];
8115            if (permissionsState.hasPermission(permission, userId)) {
8116                tmp[i] = true;
8117                numMatch++;
8118            } else {
8119                tmp[i] = false;
8120            }
8121        }
8122        if (numMatch == 0) {
8123            return;
8124        }
8125        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8126
8127        // The above might return null in cases of uninstalled apps or install-state
8128        // skew across users/profiles.
8129        if (pi != null) {
8130            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
8131                if (numMatch == permissions.length) {
8132                    pi.requestedPermissions = permissions;
8133                } else {
8134                    pi.requestedPermissions = new String[numMatch];
8135                    numMatch = 0;
8136                    for (int i=0; i<permissions.length; i++) {
8137                        if (tmp[i]) {
8138                            pi.requestedPermissions[numMatch] = permissions[i];
8139                            numMatch++;
8140                        }
8141                    }
8142                }
8143            }
8144            list.add(pi);
8145        }
8146    }
8147
8148    @Override
8149    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
8150            String[] permissions, int flags, int userId) {
8151        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8152        flags = updateFlagsForPackage(flags, userId, permissions);
8153        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8154                true /* requireFullPermission */, false /* checkShell */,
8155                "get packages holding permissions");
8156        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8157
8158        // writer
8159        synchronized (mPackages) {
8160            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
8161            boolean[] tmpBools = new boolean[permissions.length];
8162            if (listUninstalled) {
8163                for (PackageSetting ps : mSettings.mPackages.values()) {
8164                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8165                            userId);
8166                }
8167            } else {
8168                for (PackageParser.Package pkg : mPackages.values()) {
8169                    PackageSetting ps = (PackageSetting)pkg.mExtras;
8170                    if (ps != null) {
8171                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8172                                userId);
8173                    }
8174                }
8175            }
8176
8177            return new ParceledListSlice<PackageInfo>(list);
8178        }
8179    }
8180
8181    @Override
8182    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
8183        final int callingUid = Binder.getCallingUid();
8184        if (getInstantAppPackageName(callingUid) != null) {
8185            return ParceledListSlice.emptyList();
8186        }
8187        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8188        flags = updateFlagsForApplication(flags, userId, null);
8189        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8190
8191        // writer
8192        synchronized (mPackages) {
8193            ArrayList<ApplicationInfo> list;
8194            if (listUninstalled) {
8195                list = new ArrayList<>(mSettings.mPackages.size());
8196                for (PackageSetting ps : mSettings.mPackages.values()) {
8197                    ApplicationInfo ai;
8198                    int effectiveFlags = flags;
8199                    if (ps.isSystem()) {
8200                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
8201                    }
8202                    if (ps.pkg != null) {
8203                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8204                            continue;
8205                        }
8206                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8207                            return null;
8208                        }
8209                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
8210                                ps.readUserState(userId), userId);
8211                        if (ai != null) {
8212                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
8213                        }
8214                    } else {
8215                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
8216                        // and already converts to externally visible package name
8217                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
8218                                callingUid, effectiveFlags, userId);
8219                    }
8220                    if (ai != null) {
8221                        list.add(ai);
8222                    }
8223                }
8224            } else {
8225                list = new ArrayList<>(mPackages.size());
8226                for (PackageParser.Package p : mPackages.values()) {
8227                    if (p.mExtras != null) {
8228                        PackageSetting ps = (PackageSetting) p.mExtras;
8229                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
8230                            continue;
8231                        }
8232                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8233                            return null;
8234                        }
8235                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8236                                ps.readUserState(userId), userId);
8237                        if (ai != null) {
8238                            ai.packageName = resolveExternalPackageNameLPr(p);
8239                            list.add(ai);
8240                        }
8241                    }
8242                }
8243            }
8244
8245            return new ParceledListSlice<>(list);
8246        }
8247    }
8248
8249    @Override
8250    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
8251        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8252            return null;
8253        }
8254        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8255                "getEphemeralApplications");
8256        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8257                true /* requireFullPermission */, false /* checkShell */,
8258                "getEphemeralApplications");
8259        synchronized (mPackages) {
8260            List<InstantAppInfo> instantApps = mInstantAppRegistry
8261                    .getInstantAppsLPr(userId);
8262            if (instantApps != null) {
8263                return new ParceledListSlice<>(instantApps);
8264            }
8265        }
8266        return null;
8267    }
8268
8269    @Override
8270    public boolean isInstantApp(String packageName, int userId) {
8271        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8272                true /* requireFullPermission */, false /* checkShell */,
8273                "isInstantApp");
8274        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8275            return false;
8276        }
8277        int callingUid = Binder.getCallingUid();
8278        if (Process.isIsolated(callingUid)) {
8279            callingUid = mIsolatedOwners.get(callingUid);
8280        }
8281
8282        synchronized (mPackages) {
8283            final PackageSetting ps = mSettings.mPackages.get(packageName);
8284            PackageParser.Package pkg = mPackages.get(packageName);
8285            final boolean returnAllowed =
8286                    ps != null
8287                    && (isCallerSameApp(packageName, callingUid)
8288                            || canViewInstantApps(callingUid, userId)
8289                            || mInstantAppRegistry.isInstantAccessGranted(
8290                                    userId, UserHandle.getAppId(callingUid), ps.appId));
8291            if (returnAllowed) {
8292                return ps.getInstantApp(userId);
8293            }
8294        }
8295        return false;
8296    }
8297
8298    @Override
8299    public byte[] getInstantAppCookie(String packageName, int userId) {
8300        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8301            return null;
8302        }
8303
8304        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8305                true /* requireFullPermission */, false /* checkShell */,
8306                "getInstantAppCookie");
8307        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8308            return null;
8309        }
8310        synchronized (mPackages) {
8311            return mInstantAppRegistry.getInstantAppCookieLPw(
8312                    packageName, userId);
8313        }
8314    }
8315
8316    @Override
8317    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8318        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8319            return true;
8320        }
8321
8322        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8323                true /* requireFullPermission */, true /* checkShell */,
8324                "setInstantAppCookie");
8325        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8326            return false;
8327        }
8328        synchronized (mPackages) {
8329            return mInstantAppRegistry.setInstantAppCookieLPw(
8330                    packageName, cookie, userId);
8331        }
8332    }
8333
8334    @Override
8335    public Bitmap getInstantAppIcon(String packageName, int userId) {
8336        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8337            return null;
8338        }
8339
8340        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8341                "getInstantAppIcon");
8342
8343        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8344                true /* requireFullPermission */, false /* checkShell */,
8345                "getInstantAppIcon");
8346
8347        synchronized (mPackages) {
8348            return mInstantAppRegistry.getInstantAppIconLPw(
8349                    packageName, userId);
8350        }
8351    }
8352
8353    private boolean isCallerSameApp(String packageName, int uid) {
8354        PackageParser.Package pkg = mPackages.get(packageName);
8355        return pkg != null
8356                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8357    }
8358
8359    @Override
8360    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8361        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8362            return ParceledListSlice.emptyList();
8363        }
8364        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8365    }
8366
8367    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8368        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8369
8370        // reader
8371        synchronized (mPackages) {
8372            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8373            final int userId = UserHandle.getCallingUserId();
8374            while (i.hasNext()) {
8375                final PackageParser.Package p = i.next();
8376                if (p.applicationInfo == null) continue;
8377
8378                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8379                        && !p.applicationInfo.isDirectBootAware();
8380                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8381                        && p.applicationInfo.isDirectBootAware();
8382
8383                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8384                        && (!mSafeMode || isSystemApp(p))
8385                        && (matchesUnaware || matchesAware)) {
8386                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
8387                    if (ps != null) {
8388                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8389                                ps.readUserState(userId), userId);
8390                        if (ai != null) {
8391                            finalList.add(ai);
8392                        }
8393                    }
8394                }
8395            }
8396        }
8397
8398        return finalList;
8399    }
8400
8401    @Override
8402    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8403        if (!sUserManager.exists(userId)) return null;
8404        flags = updateFlagsForComponent(flags, userId, name);
8405        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
8406        // reader
8407        synchronized (mPackages) {
8408            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8409            PackageSetting ps = provider != null
8410                    ? mSettings.mPackages.get(provider.owner.packageName)
8411                    : null;
8412            if (ps != null) {
8413                final boolean isInstantApp = ps.getInstantApp(userId);
8414                // normal application; filter out instant application provider
8415                if (instantAppPkgName == null && isInstantApp) {
8416                    return null;
8417                }
8418                // instant application; filter out other instant applications
8419                if (instantAppPkgName != null
8420                        && isInstantApp
8421                        && !provider.owner.packageName.equals(instantAppPkgName)) {
8422                    return null;
8423                }
8424                // instant application; filter out non-exposed provider
8425                if (instantAppPkgName != null
8426                        && !isInstantApp
8427                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
8428                    return null;
8429                }
8430                // provider not enabled
8431                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8432                    return null;
8433                }
8434                return PackageParser.generateProviderInfo(
8435                        provider, flags, ps.readUserState(userId), userId);
8436            }
8437            return null;
8438        }
8439    }
8440
8441    /**
8442     * @deprecated
8443     */
8444    @Deprecated
8445    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8446        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8447            return;
8448        }
8449        // reader
8450        synchronized (mPackages) {
8451            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8452                    .entrySet().iterator();
8453            final int userId = UserHandle.getCallingUserId();
8454            while (i.hasNext()) {
8455                Map.Entry<String, PackageParser.Provider> entry = i.next();
8456                PackageParser.Provider p = entry.getValue();
8457                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8458
8459                if (ps != null && p.syncable
8460                        && (!mSafeMode || (p.info.applicationInfo.flags
8461                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8462                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8463                            ps.readUserState(userId), userId);
8464                    if (info != null) {
8465                        outNames.add(entry.getKey());
8466                        outInfo.add(info);
8467                    }
8468                }
8469            }
8470        }
8471    }
8472
8473    @Override
8474    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8475            int uid, int flags, String metaDataKey) {
8476        final int callingUid = Binder.getCallingUid();
8477        final int userId = processName != null ? UserHandle.getUserId(uid)
8478                : UserHandle.getCallingUserId();
8479        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8480        flags = updateFlagsForComponent(flags, userId, processName);
8481        ArrayList<ProviderInfo> finalList = null;
8482        // reader
8483        synchronized (mPackages) {
8484            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8485            while (i.hasNext()) {
8486                final PackageParser.Provider p = i.next();
8487                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8488                if (ps != null && p.info.authority != null
8489                        && (processName == null
8490                                || (p.info.processName.equals(processName)
8491                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8492                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8493
8494                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8495                    // parameter.
8496                    if (metaDataKey != null
8497                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8498                        continue;
8499                    }
8500                    final ComponentName component =
8501                            new ComponentName(p.info.packageName, p.info.name);
8502                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8503                        continue;
8504                    }
8505                    if (finalList == null) {
8506                        finalList = new ArrayList<ProviderInfo>(3);
8507                    }
8508                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8509                            ps.readUserState(userId), userId);
8510                    if (info != null) {
8511                        finalList.add(info);
8512                    }
8513                }
8514            }
8515        }
8516
8517        if (finalList != null) {
8518            Collections.sort(finalList, mProviderInitOrderSorter);
8519            return new ParceledListSlice<ProviderInfo>(finalList);
8520        }
8521
8522        return ParceledListSlice.emptyList();
8523    }
8524
8525    @Override
8526    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8527        // reader
8528        synchronized (mPackages) {
8529            final int callingUid = Binder.getCallingUid();
8530            final int callingUserId = UserHandle.getUserId(callingUid);
8531            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8532            if (ps == null) return null;
8533            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8534                return null;
8535            }
8536            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8537            return PackageParser.generateInstrumentationInfo(i, flags);
8538        }
8539    }
8540
8541    @Override
8542    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8543            String targetPackage, int flags) {
8544        final int callingUid = Binder.getCallingUid();
8545        final int callingUserId = UserHandle.getUserId(callingUid);
8546        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8547        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8548            return ParceledListSlice.emptyList();
8549        }
8550        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8551    }
8552
8553    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8554            int flags) {
8555        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8556
8557        // reader
8558        synchronized (mPackages) {
8559            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8560            while (i.hasNext()) {
8561                final PackageParser.Instrumentation p = i.next();
8562                if (targetPackage == null
8563                        || targetPackage.equals(p.info.targetPackage)) {
8564                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8565                            flags);
8566                    if (ii != null) {
8567                        finalList.add(ii);
8568                    }
8569                }
8570            }
8571        }
8572
8573        return finalList;
8574    }
8575
8576    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
8577        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
8578        try {
8579            scanDirLI(dir, parseFlags, scanFlags, currentTime);
8580        } finally {
8581            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8582        }
8583    }
8584
8585    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
8586        final File[] files = dir.listFiles();
8587        if (ArrayUtils.isEmpty(files)) {
8588            Log.d(TAG, "No files in app dir " + dir);
8589            return;
8590        }
8591
8592        if (DEBUG_PACKAGE_SCANNING) {
8593            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
8594                    + " flags=0x" + Integer.toHexString(parseFlags));
8595        }
8596        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
8597                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
8598                mParallelPackageParserCallback);
8599
8600        // Submit files for parsing in parallel
8601        int fileCount = 0;
8602        for (File file : files) {
8603            final boolean isPackage = (isApkFile(file) || file.isDirectory())
8604                    && !PackageInstallerService.isStageName(file.getName());
8605            if (!isPackage) {
8606                // Ignore entries which are not packages
8607                continue;
8608            }
8609            parallelPackageParser.submit(file, parseFlags);
8610            fileCount++;
8611        }
8612
8613        // Process results one by one
8614        for (; fileCount > 0; fileCount--) {
8615            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
8616            Throwable throwable = parseResult.throwable;
8617            int errorCode = PackageManager.INSTALL_SUCCEEDED;
8618
8619            if (throwable == null) {
8620                // Static shared libraries have synthetic package names
8621                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
8622                    renameStaticSharedLibraryPackage(parseResult.pkg);
8623                }
8624                try {
8625                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
8626                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
8627                                currentTime, null);
8628                    }
8629                } catch (PackageManagerException e) {
8630                    errorCode = e.error;
8631                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
8632                }
8633            } else if (throwable instanceof PackageParser.PackageParserException) {
8634                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
8635                        throwable;
8636                errorCode = e.error;
8637                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
8638            } else {
8639                throw new IllegalStateException("Unexpected exception occurred while parsing "
8640                        + parseResult.scanFile, throwable);
8641            }
8642
8643            // Delete invalid userdata apps
8644            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
8645                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
8646                logCriticalInfo(Log.WARN,
8647                        "Deleting invalid package at " + parseResult.scanFile);
8648                removeCodePathLI(parseResult.scanFile);
8649            }
8650        }
8651        parallelPackageParser.close();
8652    }
8653
8654    private static File getSettingsProblemFile() {
8655        File dataDir = Environment.getDataDirectory();
8656        File systemDir = new File(dataDir, "system");
8657        File fname = new File(systemDir, "uiderrors.txt");
8658        return fname;
8659    }
8660
8661    static void reportSettingsProblem(int priority, String msg) {
8662        logCriticalInfo(priority, msg);
8663    }
8664
8665    public static void logCriticalInfo(int priority, String msg) {
8666        Slog.println(priority, TAG, msg);
8667        EventLogTags.writePmCriticalInfo(msg);
8668        try {
8669            File fname = getSettingsProblemFile();
8670            FileOutputStream out = new FileOutputStream(fname, true);
8671            PrintWriter pw = new FastPrintWriter(out);
8672            SimpleDateFormat formatter = new SimpleDateFormat();
8673            String dateString = formatter.format(new Date(System.currentTimeMillis()));
8674            pw.println(dateString + ": " + msg);
8675            pw.close();
8676            FileUtils.setPermissions(
8677                    fname.toString(),
8678                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
8679                    -1, -1);
8680        } catch (java.io.IOException e) {
8681        }
8682    }
8683
8684    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
8685        if (srcFile.isDirectory()) {
8686            final File baseFile = new File(pkg.baseCodePath);
8687            long maxModifiedTime = baseFile.lastModified();
8688            if (pkg.splitCodePaths != null) {
8689                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
8690                    final File splitFile = new File(pkg.splitCodePaths[i]);
8691                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
8692                }
8693            }
8694            return maxModifiedTime;
8695        }
8696        return srcFile.lastModified();
8697    }
8698
8699    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
8700            final int policyFlags) throws PackageManagerException {
8701        // When upgrading from pre-N MR1, verify the package time stamp using the package
8702        // directory and not the APK file.
8703        final long lastModifiedTime = mIsPreNMR1Upgrade
8704                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
8705        if (ps != null
8706                && ps.codePath.equals(srcFile)
8707                && ps.timeStamp == lastModifiedTime
8708                && !isCompatSignatureUpdateNeeded(pkg)
8709                && !isRecoverSignatureUpdateNeeded(pkg)) {
8710            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
8711            KeySetManagerService ksms = mSettings.mKeySetManagerService;
8712            ArraySet<PublicKey> signingKs;
8713            synchronized (mPackages) {
8714                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
8715            }
8716            if (ps.signatures.mSignatures != null
8717                    && ps.signatures.mSignatures.length != 0
8718                    && signingKs != null) {
8719                // Optimization: reuse the existing cached certificates
8720                // if the package appears to be unchanged.
8721                pkg.mSignatures = ps.signatures.mSignatures;
8722                pkg.mSigningKeys = signingKs;
8723                return;
8724            }
8725
8726            Slog.w(TAG, "PackageSetting for " + ps.name
8727                    + " is missing signatures.  Collecting certs again to recover them.");
8728        } else {
8729            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
8730        }
8731
8732        try {
8733            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
8734            PackageParser.collectCertificates(pkg, policyFlags);
8735        } catch (PackageParserException e) {
8736            throw PackageManagerException.from(e);
8737        } finally {
8738            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8739        }
8740    }
8741
8742    /**
8743     *  Traces a package scan.
8744     *  @see #scanPackageLI(File, int, int, long, UserHandle)
8745     */
8746    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
8747            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8748        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
8749        try {
8750            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
8751        } finally {
8752            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8753        }
8754    }
8755
8756    /**
8757     *  Scans a package and returns the newly parsed package.
8758     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
8759     */
8760    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
8761            long currentTime, UserHandle user) throws PackageManagerException {
8762        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
8763        PackageParser pp = new PackageParser();
8764        pp.setSeparateProcesses(mSeparateProcesses);
8765        pp.setOnlyCoreApps(mOnlyCore);
8766        pp.setDisplayMetrics(mMetrics);
8767        pp.setCallback(mPackageParserCallback);
8768
8769        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
8770            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
8771        }
8772
8773        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
8774        final PackageParser.Package pkg;
8775        try {
8776            pkg = pp.parsePackage(scanFile, parseFlags);
8777        } catch (PackageParserException e) {
8778            throw PackageManagerException.from(e);
8779        } finally {
8780            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8781        }
8782
8783        // Static shared libraries have synthetic package names
8784        if (pkg.applicationInfo.isStaticSharedLibrary()) {
8785            renameStaticSharedLibraryPackage(pkg);
8786        }
8787
8788        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
8789    }
8790
8791    /**
8792     *  Scans a package and returns the newly parsed package.
8793     *  @throws PackageManagerException on a parse error.
8794     */
8795    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
8796            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8797            throws PackageManagerException {
8798        // If the package has children and this is the first dive in the function
8799        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
8800        // packages (parent and children) would be successfully scanned before the
8801        // actual scan since scanning mutates internal state and we want to atomically
8802        // install the package and its children.
8803        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8804            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8805                scanFlags |= SCAN_CHECK_ONLY;
8806            }
8807        } else {
8808            scanFlags &= ~SCAN_CHECK_ONLY;
8809        }
8810
8811        // Scan the parent
8812        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
8813                scanFlags, currentTime, user);
8814
8815        // Scan the children
8816        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8817        for (int i = 0; i < childCount; i++) {
8818            PackageParser.Package childPackage = pkg.childPackages.get(i);
8819            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
8820                    currentTime, user);
8821        }
8822
8823
8824        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8825            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
8826        }
8827
8828        return scannedPkg;
8829    }
8830
8831    /**
8832     *  Scans a package and returns the newly parsed package.
8833     *  @throws PackageManagerException on a parse error.
8834     */
8835    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
8836            int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8837            throws PackageManagerException {
8838        PackageSetting ps = null;
8839        PackageSetting updatedPkg;
8840        // reader
8841        synchronized (mPackages) {
8842            // Look to see if we already know about this package.
8843            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
8844            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
8845                // This package has been renamed to its original name.  Let's
8846                // use that.
8847                ps = mSettings.getPackageLPr(oldName);
8848            }
8849            // If there was no original package, see one for the real package name.
8850            if (ps == null) {
8851                ps = mSettings.getPackageLPr(pkg.packageName);
8852            }
8853            // Check to see if this package could be hiding/updating a system
8854            // package.  Must look for it either under the original or real
8855            // package name depending on our state.
8856            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
8857            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
8858
8859            // If this is a package we don't know about on the system partition, we
8860            // may need to remove disabled child packages on the system partition
8861            // or may need to not add child packages if the parent apk is updated
8862            // on the data partition and no longer defines this child package.
8863            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
8864                // If this is a parent package for an updated system app and this system
8865                // app got an OTA update which no longer defines some of the child packages
8866                // we have to prune them from the disabled system packages.
8867                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8868                if (disabledPs != null) {
8869                    final int scannedChildCount = (pkg.childPackages != null)
8870                            ? pkg.childPackages.size() : 0;
8871                    final int disabledChildCount = disabledPs.childPackageNames != null
8872                            ? disabledPs.childPackageNames.size() : 0;
8873                    for (int i = 0; i < disabledChildCount; i++) {
8874                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
8875                        boolean disabledPackageAvailable = false;
8876                        for (int j = 0; j < scannedChildCount; j++) {
8877                            PackageParser.Package childPkg = pkg.childPackages.get(j);
8878                            if (childPkg.packageName.equals(disabledChildPackageName)) {
8879                                disabledPackageAvailable = true;
8880                                break;
8881                            }
8882                         }
8883                         if (!disabledPackageAvailable) {
8884                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
8885                         }
8886                    }
8887                }
8888            }
8889        }
8890
8891        boolean updatedPkgBetter = false;
8892        // First check if this is a system package that may involve an update
8893        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
8894            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
8895            // it needs to drop FLAG_PRIVILEGED.
8896            if (locationIsPrivileged(scanFile)) {
8897                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8898            } else {
8899                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8900            }
8901
8902            if (ps != null && !ps.codePath.equals(scanFile)) {
8903                // The path has changed from what was last scanned...  check the
8904                // version of the new path against what we have stored to determine
8905                // what to do.
8906                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
8907                if (pkg.mVersionCode <= ps.versionCode) {
8908                    // The system package has been updated and the code path does not match
8909                    // Ignore entry. Skip it.
8910                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
8911                            + " ignored: updated version " + ps.versionCode
8912                            + " better than this " + pkg.mVersionCode);
8913                    if (!updatedPkg.codePath.equals(scanFile)) {
8914                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
8915                                + ps.name + " changing from " + updatedPkg.codePathString
8916                                + " to " + scanFile);
8917                        updatedPkg.codePath = scanFile;
8918                        updatedPkg.codePathString = scanFile.toString();
8919                        updatedPkg.resourcePath = scanFile;
8920                        updatedPkg.resourcePathString = scanFile.toString();
8921                    }
8922                    updatedPkg.pkg = pkg;
8923                    updatedPkg.versionCode = pkg.mVersionCode;
8924
8925                    // Update the disabled system child packages to point to the package too.
8926                    final int childCount = updatedPkg.childPackageNames != null
8927                            ? updatedPkg.childPackageNames.size() : 0;
8928                    for (int i = 0; i < childCount; i++) {
8929                        String childPackageName = updatedPkg.childPackageNames.get(i);
8930                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
8931                                childPackageName);
8932                        if (updatedChildPkg != null) {
8933                            updatedChildPkg.pkg = pkg;
8934                            updatedChildPkg.versionCode = pkg.mVersionCode;
8935                        }
8936                    }
8937
8938                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
8939                            + scanFile + " ignored: updated version " + ps.versionCode
8940                            + " better than this " + pkg.mVersionCode);
8941                } else {
8942                    // The current app on the system partition is better than
8943                    // what we have updated to on the data partition; switch
8944                    // back to the system partition version.
8945                    // At this point, its safely assumed that package installation for
8946                    // apps in system partition will go through. If not there won't be a working
8947                    // version of the app
8948                    // writer
8949                    synchronized (mPackages) {
8950                        // Just remove the loaded entries from package lists.
8951                        mPackages.remove(ps.name);
8952                    }
8953
8954                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
8955                            + " reverting from " + ps.codePathString
8956                            + ": new version " + pkg.mVersionCode
8957                            + " better than installed " + ps.versionCode);
8958
8959                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
8960                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
8961                    synchronized (mInstallLock) {
8962                        args.cleanUpResourcesLI();
8963                    }
8964                    synchronized (mPackages) {
8965                        mSettings.enableSystemPackageLPw(ps.name);
8966                    }
8967                    updatedPkgBetter = true;
8968                }
8969            }
8970        }
8971
8972        if (updatedPkg != null) {
8973            // An updated system app will not have the PARSE_IS_SYSTEM flag set
8974            // initially
8975            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
8976
8977            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
8978            // flag set initially
8979            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
8980                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
8981            }
8982        }
8983
8984        // Verify certificates against what was last scanned
8985        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
8986
8987        /*
8988         * A new system app appeared, but we already had a non-system one of the
8989         * same name installed earlier.
8990         */
8991        boolean shouldHideSystemApp = false;
8992        if (updatedPkg == null && ps != null
8993                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
8994            /*
8995             * Check to make sure the signatures match first. If they don't,
8996             * wipe the installed application and its data.
8997             */
8998            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
8999                    != PackageManager.SIGNATURE_MATCH) {
9000                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
9001                        + " signatures don't match existing userdata copy; removing");
9002                try (PackageFreezer freezer = freezePackage(pkg.packageName,
9003                        "scanPackageInternalLI")) {
9004                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
9005                }
9006                ps = null;
9007            } else {
9008                /*
9009                 * If the newly-added system app is an older version than the
9010                 * already installed version, hide it. It will be scanned later
9011                 * and re-added like an update.
9012                 */
9013                if (pkg.mVersionCode <= ps.versionCode) {
9014                    shouldHideSystemApp = true;
9015                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
9016                            + " but new version " + pkg.mVersionCode + " better than installed "
9017                            + ps.versionCode + "; hiding system");
9018                } else {
9019                    /*
9020                     * The newly found system app is a newer version that the
9021                     * one previously installed. Simply remove the
9022                     * already-installed application and replace it with our own
9023                     * while keeping the application data.
9024                     */
9025                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
9026                            + " reverting from " + ps.codePathString + ": new version "
9027                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
9028                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
9029                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
9030                    synchronized (mInstallLock) {
9031                        args.cleanUpResourcesLI();
9032                    }
9033                }
9034            }
9035        }
9036
9037        // The apk is forward locked (not public) if its code and resources
9038        // are kept in different files. (except for app in either system or
9039        // vendor path).
9040        // TODO grab this value from PackageSettings
9041        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9042            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
9043                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
9044            }
9045        }
9046
9047        // TODO: extend to support forward-locked splits
9048        String resourcePath = null;
9049        String baseResourcePath = null;
9050        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
9051            if (ps != null && ps.resourcePathString != null) {
9052                resourcePath = ps.resourcePathString;
9053                baseResourcePath = ps.resourcePathString;
9054            } else {
9055                // Should not happen at all. Just log an error.
9056                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
9057            }
9058        } else {
9059            resourcePath = pkg.codePath;
9060            baseResourcePath = pkg.baseCodePath;
9061        }
9062
9063        // Set application objects path explicitly.
9064        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
9065        pkg.setApplicationInfoCodePath(pkg.codePath);
9066        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
9067        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
9068        pkg.setApplicationInfoResourcePath(resourcePath);
9069        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
9070        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
9071
9072        final int userId = ((user == null) ? 0 : user.getIdentifier());
9073        if (ps != null && ps.getInstantApp(userId)) {
9074            scanFlags |= SCAN_AS_INSTANT_APP;
9075        }
9076
9077        // Note that we invoke the following method only if we are about to unpack an application
9078        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
9079                | SCAN_UPDATE_SIGNATURE, currentTime, user);
9080
9081        /*
9082         * If the system app should be overridden by a previously installed
9083         * data, hide the system app now and let the /data/app scan pick it up
9084         * again.
9085         */
9086        if (shouldHideSystemApp) {
9087            synchronized (mPackages) {
9088                mSettings.disableSystemPackageLPw(pkg.packageName, true);
9089            }
9090        }
9091
9092        return scannedPkg;
9093    }
9094
9095    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
9096        // Derive the new package synthetic package name
9097        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
9098                + pkg.staticSharedLibVersion);
9099    }
9100
9101    private static String fixProcessName(String defProcessName,
9102            String processName) {
9103        if (processName == null) {
9104            return defProcessName;
9105        }
9106        return processName;
9107    }
9108
9109    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
9110            throws PackageManagerException {
9111        if (pkgSetting.signatures.mSignatures != null) {
9112            // Already existing package. Make sure signatures match
9113            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
9114                    == PackageManager.SIGNATURE_MATCH;
9115            if (!match) {
9116                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
9117                        == PackageManager.SIGNATURE_MATCH;
9118            }
9119            if (!match) {
9120                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
9121                        == PackageManager.SIGNATURE_MATCH;
9122            }
9123            if (!match) {
9124                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
9125                        + pkg.packageName + " signatures do not match the "
9126                        + "previously installed version; ignoring!");
9127            }
9128        }
9129
9130        // Check for shared user signatures
9131        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
9132            // Already existing package. Make sure signatures match
9133            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
9134                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
9135            if (!match) {
9136                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
9137                        == PackageManager.SIGNATURE_MATCH;
9138            }
9139            if (!match) {
9140                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
9141                        == PackageManager.SIGNATURE_MATCH;
9142            }
9143            if (!match) {
9144                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
9145                        "Package " + pkg.packageName
9146                        + " has no signatures that match those in shared user "
9147                        + pkgSetting.sharedUser.name + "; ignoring!");
9148            }
9149        }
9150    }
9151
9152    /**
9153     * Enforces that only the system UID or root's UID can call a method exposed
9154     * via Binder.
9155     *
9156     * @param message used as message if SecurityException is thrown
9157     * @throws SecurityException if the caller is not system or root
9158     */
9159    private static final void enforceSystemOrRoot(String message) {
9160        final int uid = Binder.getCallingUid();
9161        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
9162            throw new SecurityException(message);
9163        }
9164    }
9165
9166    @Override
9167    public void performFstrimIfNeeded() {
9168        enforceSystemOrRoot("Only the system can request fstrim");
9169
9170        // Before everything else, see whether we need to fstrim.
9171        try {
9172            IStorageManager sm = PackageHelper.getStorageManager();
9173            if (sm != null) {
9174                boolean doTrim = false;
9175                final long interval = android.provider.Settings.Global.getLong(
9176                        mContext.getContentResolver(),
9177                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
9178                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
9179                if (interval > 0) {
9180                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
9181                    if (timeSinceLast > interval) {
9182                        doTrim = true;
9183                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
9184                                + "; running immediately");
9185                    }
9186                }
9187                if (doTrim) {
9188                    final boolean dexOptDialogShown;
9189                    synchronized (mPackages) {
9190                        dexOptDialogShown = mDexOptDialogShown;
9191                    }
9192                    if (!isFirstBoot() && dexOptDialogShown) {
9193                        try {
9194                            ActivityManager.getService().showBootMessage(
9195                                    mContext.getResources().getString(
9196                                            R.string.android_upgrading_fstrim), true);
9197                        } catch (RemoteException e) {
9198                        }
9199                    }
9200                    sm.runMaintenance();
9201                }
9202            } else {
9203                Slog.e(TAG, "storageManager service unavailable!");
9204            }
9205        } catch (RemoteException e) {
9206            // Can't happen; StorageManagerService is local
9207        }
9208    }
9209
9210    @Override
9211    public void updatePackagesIfNeeded() {
9212        enforceSystemOrRoot("Only the system can request package update");
9213
9214        // We need to re-extract after an OTA.
9215        boolean causeUpgrade = isUpgrade();
9216
9217        // First boot or factory reset.
9218        // Note: we also handle devices that are upgrading to N right now as if it is their
9219        //       first boot, as they do not have profile data.
9220        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
9221
9222        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
9223        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
9224
9225        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
9226            return;
9227        }
9228
9229        List<PackageParser.Package> pkgs;
9230        synchronized (mPackages) {
9231            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
9232        }
9233
9234        final long startTime = System.nanoTime();
9235        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
9236                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
9237
9238        final int elapsedTimeSeconds =
9239                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
9240
9241        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
9242        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
9243        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
9244        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
9245        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
9246    }
9247
9248    /**
9249     * Performs dexopt on the set of packages in {@code packages} and returns an int array
9250     * containing statistics about the invocation. The array consists of three elements,
9251     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
9252     * and {@code numberOfPackagesFailed}.
9253     */
9254    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
9255            String compilerFilter) {
9256
9257        int numberOfPackagesVisited = 0;
9258        int numberOfPackagesOptimized = 0;
9259        int numberOfPackagesSkipped = 0;
9260        int numberOfPackagesFailed = 0;
9261        final int numberOfPackagesToDexopt = pkgs.size();
9262
9263        for (PackageParser.Package pkg : pkgs) {
9264            numberOfPackagesVisited++;
9265
9266            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
9267                if (DEBUG_DEXOPT) {
9268                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
9269                }
9270                numberOfPackagesSkipped++;
9271                continue;
9272            }
9273
9274            if (DEBUG_DEXOPT) {
9275                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
9276                        numberOfPackagesToDexopt + ": " + pkg.packageName);
9277            }
9278
9279            if (showDialog) {
9280                try {
9281                    ActivityManager.getService().showBootMessage(
9282                            mContext.getResources().getString(R.string.android_upgrading_apk,
9283                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
9284                } catch (RemoteException e) {
9285                }
9286                synchronized (mPackages) {
9287                    mDexOptDialogShown = true;
9288                }
9289            }
9290
9291            // If the OTA updates a system app which was previously preopted to a non-preopted state
9292            // the app might end up being verified at runtime. That's because by default the apps
9293            // are verify-profile but for preopted apps there's no profile.
9294            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
9295            // that before the OTA the app was preopted) the app gets compiled with a non-profile
9296            // filter (by default 'quicken').
9297            // Note that at this stage unused apps are already filtered.
9298            if (isSystemApp(pkg) &&
9299                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
9300                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
9301                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
9302            }
9303
9304            // checkProfiles is false to avoid merging profiles during boot which
9305            // might interfere with background compilation (b/28612421).
9306            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
9307            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
9308            // trade-off worth doing to save boot time work.
9309            int dexOptStatus = performDexOptTraced(pkg.packageName,
9310                    false /* checkProfiles */,
9311                    compilerFilter,
9312                    false /* force */);
9313            switch (dexOptStatus) {
9314                case PackageDexOptimizer.DEX_OPT_PERFORMED:
9315                    numberOfPackagesOptimized++;
9316                    break;
9317                case PackageDexOptimizer.DEX_OPT_SKIPPED:
9318                    numberOfPackagesSkipped++;
9319                    break;
9320                case PackageDexOptimizer.DEX_OPT_FAILED:
9321                    numberOfPackagesFailed++;
9322                    break;
9323                default:
9324                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
9325                    break;
9326            }
9327        }
9328
9329        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
9330                numberOfPackagesFailed };
9331    }
9332
9333    @Override
9334    public void notifyPackageUse(String packageName, int reason) {
9335        synchronized (mPackages) {
9336            final int callingUid = Binder.getCallingUid();
9337            final int callingUserId = UserHandle.getUserId(callingUid);
9338            if (getInstantAppPackageName(callingUid) != null) {
9339                if (!isCallerSameApp(packageName, callingUid)) {
9340                    return;
9341                }
9342            } else {
9343                if (isInstantApp(packageName, callingUserId)) {
9344                    return;
9345                }
9346            }
9347            final PackageParser.Package p = mPackages.get(packageName);
9348            if (p == null) {
9349                return;
9350            }
9351            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9352        }
9353    }
9354
9355    @Override
9356    public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) {
9357        int userId = UserHandle.getCallingUserId();
9358        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9359        if (ai == null) {
9360            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9361                + loadingPackageName + ", user=" + userId);
9362            return;
9363        }
9364        mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId);
9365    }
9366
9367    @Override
9368    public boolean performDexOpt(String packageName,
9369            boolean checkProfiles, int compileReason, boolean force) {
9370        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9371            return false;
9372        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9373            return false;
9374        }
9375        return performDexOptWithStatus(packageName, checkProfiles, compileReason, force) !=
9376                PackageDexOptimizer.DEX_OPT_FAILED;
9377    }
9378
9379    /**
9380     * Perform dexopt on the given package and return one of following result:
9381     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9382     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9383     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
9384     */
9385    /* package */ int performDexOptWithStatus(String packageName,
9386            boolean checkProfiles, int compileReason, boolean force) {
9387        return performDexOptTraced(packageName, checkProfiles,
9388                getCompilerFilterForReason(compileReason), force);
9389    }
9390
9391    @Override
9392    public boolean performDexOptMode(String packageName,
9393            boolean checkProfiles, String targetCompilerFilter, boolean force) {
9394        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9395            return false;
9396        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9397            return false;
9398        }
9399        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
9400                targetCompilerFilter, force);
9401        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9402    }
9403
9404    private int performDexOptTraced(String packageName,
9405                boolean checkProfiles, String targetCompilerFilter, boolean force) {
9406        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9407        try {
9408            return performDexOptInternal(packageName, checkProfiles,
9409                    targetCompilerFilter, force);
9410        } finally {
9411            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9412        }
9413    }
9414
9415    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
9416    // if the package can now be considered up to date for the given filter.
9417    private int performDexOptInternal(String packageName,
9418                boolean checkProfiles, String targetCompilerFilter, boolean force) {
9419        PackageParser.Package p;
9420        synchronized (mPackages) {
9421            p = mPackages.get(packageName);
9422            if (p == null) {
9423                // Package could not be found. Report failure.
9424                return PackageDexOptimizer.DEX_OPT_FAILED;
9425            }
9426            mPackageUsage.maybeWriteAsync(mPackages);
9427            mCompilerStats.maybeWriteAsync();
9428        }
9429        long callingId = Binder.clearCallingIdentity();
9430        try {
9431            synchronized (mInstallLock) {
9432                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
9433                        targetCompilerFilter, force);
9434            }
9435        } finally {
9436            Binder.restoreCallingIdentity(callingId);
9437        }
9438    }
9439
9440    public ArraySet<String> getOptimizablePackages() {
9441        ArraySet<String> pkgs = new ArraySet<String>();
9442        synchronized (mPackages) {
9443            for (PackageParser.Package p : mPackages.values()) {
9444                if (PackageDexOptimizer.canOptimizePackage(p)) {
9445                    pkgs.add(p.packageName);
9446                }
9447            }
9448        }
9449        return pkgs;
9450    }
9451
9452    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
9453            boolean checkProfiles, String targetCompilerFilter,
9454            boolean force) {
9455        // Select the dex optimizer based on the force parameter.
9456        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
9457        //       allocate an object here.
9458        PackageDexOptimizer pdo = force
9459                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
9460                : mPackageDexOptimizer;
9461
9462        // Dexopt all dependencies first. Note: we ignore the return value and march on
9463        // on errors.
9464        // Note that we are going to call performDexOpt on those libraries as many times as
9465        // they are referenced in packages. When we do a batch of performDexOpt (for example
9466        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
9467        // and the first package that uses the library will dexopt it. The
9468        // others will see that the compiled code for the library is up to date.
9469        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
9470        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
9471        if (!deps.isEmpty()) {
9472            for (PackageParser.Package depPackage : deps) {
9473                // TODO: Analyze and investigate if we (should) profile libraries.
9474                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
9475                        false /* checkProfiles */,
9476                        targetCompilerFilter,
9477                        getOrCreateCompilerPackageStats(depPackage),
9478                        true /* isUsedByOtherApps */);
9479            }
9480        }
9481        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
9482                targetCompilerFilter, getOrCreateCompilerPackageStats(p),
9483                mDexManager.isUsedByOtherApps(p.packageName));
9484    }
9485
9486    // Performs dexopt on the used secondary dex files belonging to the given package.
9487    // Returns true if all dex files were process successfully (which could mean either dexopt or
9488    // skip). Returns false if any of the files caused errors.
9489    @Override
9490    public boolean performDexOptSecondary(String packageName, String compilerFilter,
9491            boolean force) {
9492        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9493            return false;
9494        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9495            return false;
9496        }
9497        mDexManager.reconcileSecondaryDexFiles(packageName);
9498        return mDexManager.dexoptSecondaryDex(packageName, compilerFilter, force);
9499    }
9500
9501    public boolean performDexOptSecondary(String packageName, int compileReason,
9502            boolean force) {
9503        return mDexManager.dexoptSecondaryDex(packageName, compileReason, force);
9504    }
9505
9506    /**
9507     * Reconcile the information we have about the secondary dex files belonging to
9508     * {@code packagName} and the actual dex files. For all dex files that were
9509     * deleted, update the internal records and delete the generated oat files.
9510     */
9511    @Override
9512    public void reconcileSecondaryDexFiles(String packageName) {
9513        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9514            return;
9515        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9516            return;
9517        }
9518        mDexManager.reconcileSecondaryDexFiles(packageName);
9519    }
9520
9521    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
9522    // a reference there.
9523    /*package*/ DexManager getDexManager() {
9524        return mDexManager;
9525    }
9526
9527    /**
9528     * Execute the background dexopt job immediately.
9529     */
9530    @Override
9531    public boolean runBackgroundDexoptJob() {
9532        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9533            return false;
9534        }
9535        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
9536    }
9537
9538    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
9539        if (p.usesLibraries != null || p.usesOptionalLibraries != null
9540                || p.usesStaticLibraries != null) {
9541            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
9542            Set<String> collectedNames = new HashSet<>();
9543            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
9544
9545            retValue.remove(p);
9546
9547            return retValue;
9548        } else {
9549            return Collections.emptyList();
9550        }
9551    }
9552
9553    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
9554            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9555        if (!collectedNames.contains(p.packageName)) {
9556            collectedNames.add(p.packageName);
9557            collected.add(p);
9558
9559            if (p.usesLibraries != null) {
9560                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
9561                        null, collected, collectedNames);
9562            }
9563            if (p.usesOptionalLibraries != null) {
9564                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
9565                        null, collected, collectedNames);
9566            }
9567            if (p.usesStaticLibraries != null) {
9568                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
9569                        p.usesStaticLibrariesVersions, collected, collectedNames);
9570            }
9571        }
9572    }
9573
9574    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
9575            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9576        final int libNameCount = libs.size();
9577        for (int i = 0; i < libNameCount; i++) {
9578            String libName = libs.get(i);
9579            int version = (versions != null && versions.length == libNameCount)
9580                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
9581            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
9582            if (libPkg != null) {
9583                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
9584            }
9585        }
9586    }
9587
9588    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
9589        synchronized (mPackages) {
9590            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
9591            if (libEntry != null) {
9592                return mPackages.get(libEntry.apk);
9593            }
9594            return null;
9595        }
9596    }
9597
9598    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
9599        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9600        if (versionedLib == null) {
9601            return null;
9602        }
9603        return versionedLib.get(version);
9604    }
9605
9606    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
9607        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9608                pkg.staticSharedLibName);
9609        if (versionedLib == null) {
9610            return null;
9611        }
9612        int previousLibVersion = -1;
9613        final int versionCount = versionedLib.size();
9614        for (int i = 0; i < versionCount; i++) {
9615            final int libVersion = versionedLib.keyAt(i);
9616            if (libVersion < pkg.staticSharedLibVersion) {
9617                previousLibVersion = Math.max(previousLibVersion, libVersion);
9618            }
9619        }
9620        if (previousLibVersion >= 0) {
9621            return versionedLib.get(previousLibVersion);
9622        }
9623        return null;
9624    }
9625
9626    public void shutdown() {
9627        mPackageUsage.writeNow(mPackages);
9628        mCompilerStats.writeNow();
9629    }
9630
9631    @Override
9632    public void dumpProfiles(String packageName) {
9633        PackageParser.Package pkg;
9634        synchronized (mPackages) {
9635            pkg = mPackages.get(packageName);
9636            if (pkg == null) {
9637                throw new IllegalArgumentException("Unknown package: " + packageName);
9638            }
9639        }
9640        /* Only the shell, root, or the app user should be able to dump profiles. */
9641        int callingUid = Binder.getCallingUid();
9642        if (callingUid != Process.SHELL_UID &&
9643            callingUid != Process.ROOT_UID &&
9644            callingUid != pkg.applicationInfo.uid) {
9645            throw new SecurityException("dumpProfiles");
9646        }
9647
9648        synchronized (mInstallLock) {
9649            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
9650            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
9651            try {
9652                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
9653                String codePaths = TextUtils.join(";", allCodePaths);
9654                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
9655            } catch (InstallerException e) {
9656                Slog.w(TAG, "Failed to dump profiles", e);
9657            }
9658            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9659        }
9660    }
9661
9662    @Override
9663    public void forceDexOpt(String packageName) {
9664        enforceSystemOrRoot("forceDexOpt");
9665
9666        PackageParser.Package pkg;
9667        synchronized (mPackages) {
9668            pkg = mPackages.get(packageName);
9669            if (pkg == null) {
9670                throw new IllegalArgumentException("Unknown package: " + packageName);
9671            }
9672        }
9673
9674        synchronized (mInstallLock) {
9675            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9676
9677            // Whoever is calling forceDexOpt wants a compiled package.
9678            // Don't use profiles since that may cause compilation to be skipped.
9679            final int res = performDexOptInternalWithDependenciesLI(pkg,
9680                    false /* checkProfiles */, getDefaultCompilerFilter(),
9681                    true /* force */);
9682
9683            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9684            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
9685                throw new IllegalStateException("Failed to dexopt: " + res);
9686            }
9687        }
9688    }
9689
9690    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
9691        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
9692            Slog.w(TAG, "Unable to update from " + oldPkg.name
9693                    + " to " + newPkg.packageName
9694                    + ": old package not in system partition");
9695            return false;
9696        } else if (mPackages.get(oldPkg.name) != null) {
9697            Slog.w(TAG, "Unable to update from " + oldPkg.name
9698                    + " to " + newPkg.packageName
9699                    + ": old package still exists");
9700            return false;
9701        }
9702        return true;
9703    }
9704
9705    void removeCodePathLI(File codePath) {
9706        if (codePath.isDirectory()) {
9707            try {
9708                mInstaller.rmPackageDir(codePath.getAbsolutePath());
9709            } catch (InstallerException e) {
9710                Slog.w(TAG, "Failed to remove code path", e);
9711            }
9712        } else {
9713            codePath.delete();
9714        }
9715    }
9716
9717    private int[] resolveUserIds(int userId) {
9718        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
9719    }
9720
9721    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9722        if (pkg == null) {
9723            Slog.wtf(TAG, "Package was null!", new Throwable());
9724            return;
9725        }
9726        clearAppDataLeafLIF(pkg, userId, flags);
9727        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9728        for (int i = 0; i < childCount; i++) {
9729            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9730        }
9731    }
9732
9733    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9734        final PackageSetting ps;
9735        synchronized (mPackages) {
9736            ps = mSettings.mPackages.get(pkg.packageName);
9737        }
9738        for (int realUserId : resolveUserIds(userId)) {
9739            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9740            try {
9741                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9742                        ceDataInode);
9743            } catch (InstallerException e) {
9744                Slog.w(TAG, String.valueOf(e));
9745            }
9746        }
9747    }
9748
9749    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9750        if (pkg == null) {
9751            Slog.wtf(TAG, "Package was null!", new Throwable());
9752            return;
9753        }
9754        destroyAppDataLeafLIF(pkg, userId, flags);
9755        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9756        for (int i = 0; i < childCount; i++) {
9757            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9758        }
9759    }
9760
9761    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9762        final PackageSetting ps;
9763        synchronized (mPackages) {
9764            ps = mSettings.mPackages.get(pkg.packageName);
9765        }
9766        for (int realUserId : resolveUserIds(userId)) {
9767            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9768            try {
9769                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9770                        ceDataInode);
9771            } catch (InstallerException e) {
9772                Slog.w(TAG, String.valueOf(e));
9773            }
9774            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
9775        }
9776    }
9777
9778    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
9779        if (pkg == null) {
9780            Slog.wtf(TAG, "Package was null!", new Throwable());
9781            return;
9782        }
9783        destroyAppProfilesLeafLIF(pkg);
9784        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9785        for (int i = 0; i < childCount; i++) {
9786            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
9787        }
9788    }
9789
9790    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
9791        try {
9792            mInstaller.destroyAppProfiles(pkg.packageName);
9793        } catch (InstallerException e) {
9794            Slog.w(TAG, String.valueOf(e));
9795        }
9796    }
9797
9798    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
9799        if (pkg == null) {
9800            Slog.wtf(TAG, "Package was null!", new Throwable());
9801            return;
9802        }
9803        clearAppProfilesLeafLIF(pkg);
9804        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9805        for (int i = 0; i < childCount; i++) {
9806            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
9807        }
9808    }
9809
9810    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
9811        try {
9812            mInstaller.clearAppProfiles(pkg.packageName);
9813        } catch (InstallerException e) {
9814            Slog.w(TAG, String.valueOf(e));
9815        }
9816    }
9817
9818    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
9819            long lastUpdateTime) {
9820        // Set parent install/update time
9821        PackageSetting ps = (PackageSetting) pkg.mExtras;
9822        if (ps != null) {
9823            ps.firstInstallTime = firstInstallTime;
9824            ps.lastUpdateTime = lastUpdateTime;
9825        }
9826        // Set children install/update time
9827        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9828        for (int i = 0; i < childCount; i++) {
9829            PackageParser.Package childPkg = pkg.childPackages.get(i);
9830            ps = (PackageSetting) childPkg.mExtras;
9831            if (ps != null) {
9832                ps.firstInstallTime = firstInstallTime;
9833                ps.lastUpdateTime = lastUpdateTime;
9834            }
9835        }
9836    }
9837
9838    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
9839            PackageParser.Package changingLib) {
9840        if (file.path != null) {
9841            usesLibraryFiles.add(file.path);
9842            return;
9843        }
9844        PackageParser.Package p = mPackages.get(file.apk);
9845        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
9846            // If we are doing this while in the middle of updating a library apk,
9847            // then we need to make sure to use that new apk for determining the
9848            // dependencies here.  (We haven't yet finished committing the new apk
9849            // to the package manager state.)
9850            if (p == null || p.packageName.equals(changingLib.packageName)) {
9851                p = changingLib;
9852            }
9853        }
9854        if (p != null) {
9855            usesLibraryFiles.addAll(p.getAllCodePaths());
9856            if (p.usesLibraryFiles != null) {
9857                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
9858            }
9859        }
9860    }
9861
9862    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
9863            PackageParser.Package changingLib) throws PackageManagerException {
9864        if (pkg == null) {
9865            return;
9866        }
9867        ArraySet<String> usesLibraryFiles = null;
9868        if (pkg.usesLibraries != null) {
9869            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
9870                    null, null, pkg.packageName, changingLib, true, null);
9871        }
9872        if (pkg.usesStaticLibraries != null) {
9873            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
9874                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
9875                    pkg.packageName, changingLib, true, usesLibraryFiles);
9876        }
9877        if (pkg.usesOptionalLibraries != null) {
9878            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
9879                    null, null, pkg.packageName, changingLib, false, usesLibraryFiles);
9880        }
9881        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
9882            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
9883        } else {
9884            pkg.usesLibraryFiles = null;
9885        }
9886    }
9887
9888    private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
9889            @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests,
9890            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
9891            boolean required, @Nullable ArraySet<String> outUsedLibraries)
9892            throws PackageManagerException {
9893        final int libCount = requestedLibraries.size();
9894        for (int i = 0; i < libCount; i++) {
9895            final String libName = requestedLibraries.get(i);
9896            final int libVersion = requiredVersions != null ? requiredVersions[i]
9897                    : SharedLibraryInfo.VERSION_UNDEFINED;
9898            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
9899            if (libEntry == null) {
9900                if (required) {
9901                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9902                            "Package " + packageName + " requires unavailable shared library "
9903                                    + libName + "; failing!");
9904                } else if (DEBUG_SHARED_LIBRARIES) {
9905                    Slog.i(TAG, "Package " + packageName
9906                            + " desires unavailable shared library "
9907                            + libName + "; ignoring!");
9908                }
9909            } else {
9910                if (requiredVersions != null && requiredCertDigests != null) {
9911                    if (libEntry.info.getVersion() != requiredVersions[i]) {
9912                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9913                            "Package " + packageName + " requires unavailable static shared"
9914                                    + " library " + libName + " version "
9915                                    + libEntry.info.getVersion() + "; failing!");
9916                    }
9917
9918                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
9919                    if (libPkg == null) {
9920                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9921                                "Package " + packageName + " requires unavailable static shared"
9922                                        + " library; failing!");
9923                    }
9924
9925                    String expectedCertDigest = requiredCertDigests[i];
9926                    String libCertDigest = PackageUtils.computeCertSha256Digest(
9927                                libPkg.mSignatures[0]);
9928                    if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) {
9929                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9930                                "Package " + packageName + " requires differently signed" +
9931                                        " static shared library; failing!");
9932                    }
9933                }
9934
9935                if (outUsedLibraries == null) {
9936                    outUsedLibraries = new ArraySet<>();
9937                }
9938                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
9939            }
9940        }
9941        return outUsedLibraries;
9942    }
9943
9944    private static boolean hasString(List<String> list, List<String> which) {
9945        if (list == null) {
9946            return false;
9947        }
9948        for (int i=list.size()-1; i>=0; i--) {
9949            for (int j=which.size()-1; j>=0; j--) {
9950                if (which.get(j).equals(list.get(i))) {
9951                    return true;
9952                }
9953            }
9954        }
9955        return false;
9956    }
9957
9958    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
9959            PackageParser.Package changingPkg) {
9960        ArrayList<PackageParser.Package> res = null;
9961        for (PackageParser.Package pkg : mPackages.values()) {
9962            if (changingPkg != null
9963                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
9964                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
9965                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
9966                            changingPkg.staticSharedLibName)) {
9967                return null;
9968            }
9969            if (res == null) {
9970                res = new ArrayList<>();
9971            }
9972            res.add(pkg);
9973            try {
9974                updateSharedLibrariesLPr(pkg, changingPkg);
9975            } catch (PackageManagerException e) {
9976                // If a system app update or an app and a required lib missing we
9977                // delete the package and for updated system apps keep the data as
9978                // it is better for the user to reinstall than to be in an limbo
9979                // state. Also libs disappearing under an app should never happen
9980                // - just in case.
9981                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
9982                    final int flags = pkg.isUpdatedSystemApp()
9983                            ? PackageManager.DELETE_KEEP_DATA : 0;
9984                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
9985                            flags , null, true, null);
9986                }
9987                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
9988            }
9989        }
9990        return res;
9991    }
9992
9993    /**
9994     * Derive the value of the {@code cpuAbiOverride} based on the provided
9995     * value and an optional stored value from the package settings.
9996     */
9997    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
9998        String cpuAbiOverride = null;
9999
10000        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
10001            cpuAbiOverride = null;
10002        } else if (abiOverride != null) {
10003            cpuAbiOverride = abiOverride;
10004        } else if (settings != null) {
10005            cpuAbiOverride = settings.cpuAbiOverrideString;
10006        }
10007
10008        return cpuAbiOverride;
10009    }
10010
10011    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
10012            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
10013                    throws PackageManagerException {
10014        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
10015        // If the package has children and this is the first dive in the function
10016        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
10017        // whether all packages (parent and children) would be successfully scanned
10018        // before the actual scan since scanning mutates internal state and we want
10019        // to atomically install the package and its children.
10020        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10021            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
10022                scanFlags |= SCAN_CHECK_ONLY;
10023            }
10024        } else {
10025            scanFlags &= ~SCAN_CHECK_ONLY;
10026        }
10027
10028        final PackageParser.Package scannedPkg;
10029        try {
10030            // Scan the parent
10031            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
10032            // Scan the children
10033            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10034            for (int i = 0; i < childCount; i++) {
10035                PackageParser.Package childPkg = pkg.childPackages.get(i);
10036                scanPackageLI(childPkg, policyFlags,
10037                        scanFlags, currentTime, user);
10038            }
10039        } finally {
10040            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10041        }
10042
10043        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10044            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
10045        }
10046
10047        return scannedPkg;
10048    }
10049
10050    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
10051            int scanFlags, long currentTime, @Nullable UserHandle user)
10052                    throws PackageManagerException {
10053        boolean success = false;
10054        try {
10055            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
10056                    currentTime, user);
10057            success = true;
10058            return res;
10059        } finally {
10060            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
10061                // DELETE_DATA_ON_FAILURES is only used by frozen paths
10062                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
10063                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
10064                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
10065            }
10066        }
10067    }
10068
10069    /**
10070     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
10071     */
10072    private static boolean apkHasCode(String fileName) {
10073        StrictJarFile jarFile = null;
10074        try {
10075            jarFile = new StrictJarFile(fileName,
10076                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
10077            return jarFile.findEntry("classes.dex") != null;
10078        } catch (IOException ignore) {
10079        } finally {
10080            try {
10081                if (jarFile != null) {
10082                    jarFile.close();
10083                }
10084            } catch (IOException ignore) {}
10085        }
10086        return false;
10087    }
10088
10089    /**
10090     * Enforces code policy for the package. This ensures that if an APK has
10091     * declared hasCode="true" in its manifest that the APK actually contains
10092     * code.
10093     *
10094     * @throws PackageManagerException If bytecode could not be found when it should exist
10095     */
10096    private static void assertCodePolicy(PackageParser.Package pkg)
10097            throws PackageManagerException {
10098        final boolean shouldHaveCode =
10099                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10100        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10101            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10102                    "Package " + pkg.baseCodePath + " code is missing");
10103        }
10104
10105        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10106            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10107                final boolean splitShouldHaveCode =
10108                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10109                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10110                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10111                            "Package " + pkg.splitCodePaths[i] + " code is missing");
10112                }
10113            }
10114        }
10115    }
10116
10117    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
10118            final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
10119                    throws PackageManagerException {
10120        if (DEBUG_PACKAGE_SCANNING) {
10121            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10122                Log.d(TAG, "Scanning package " + pkg.packageName);
10123        }
10124
10125        applyPolicy(pkg, policyFlags);
10126
10127        assertPackageIsValid(pkg, policyFlags, scanFlags);
10128
10129        // Initialize package source and resource directories
10130        final File scanFile = new File(pkg.codePath);
10131        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10132        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10133
10134        SharedUserSetting suid = null;
10135        PackageSetting pkgSetting = null;
10136
10137        // Getting the package setting may have a side-effect, so if we
10138        // are only checking if scan would succeed, stash a copy of the
10139        // old setting to restore at the end.
10140        PackageSetting nonMutatedPs = null;
10141
10142        // We keep references to the derived CPU Abis from settings in oder to reuse
10143        // them in the case where we're not upgrading or booting for the first time.
10144        String primaryCpuAbiFromSettings = null;
10145        String secondaryCpuAbiFromSettings = null;
10146
10147        // writer
10148        synchronized (mPackages) {
10149            if (pkg.mSharedUserId != null) {
10150                // SIDE EFFECTS; may potentially allocate a new shared user
10151                suid = mSettings.getSharedUserLPw(
10152                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
10153                if (DEBUG_PACKAGE_SCANNING) {
10154                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10155                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
10156                                + "): packages=" + suid.packages);
10157                }
10158            }
10159
10160            // Check if we are renaming from an original package name.
10161            PackageSetting origPackage = null;
10162            String realName = null;
10163            if (pkg.mOriginalPackages != null) {
10164                // This package may need to be renamed to a previously
10165                // installed name.  Let's check on that...
10166                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
10167                if (pkg.mOriginalPackages.contains(renamed)) {
10168                    // This package had originally been installed as the
10169                    // original name, and we have already taken care of
10170                    // transitioning to the new one.  Just update the new
10171                    // one to continue using the old name.
10172                    realName = pkg.mRealPackage;
10173                    if (!pkg.packageName.equals(renamed)) {
10174                        // Callers into this function may have already taken
10175                        // care of renaming the package; only do it here if
10176                        // it is not already done.
10177                        pkg.setPackageName(renamed);
10178                    }
10179                } else {
10180                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
10181                        if ((origPackage = mSettings.getPackageLPr(
10182                                pkg.mOriginalPackages.get(i))) != null) {
10183                            // We do have the package already installed under its
10184                            // original name...  should we use it?
10185                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
10186                                // New package is not compatible with original.
10187                                origPackage = null;
10188                                continue;
10189                            } else if (origPackage.sharedUser != null) {
10190                                // Make sure uid is compatible between packages.
10191                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
10192                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
10193                                            + " to " + pkg.packageName + ": old uid "
10194                                            + origPackage.sharedUser.name
10195                                            + " differs from " + pkg.mSharedUserId);
10196                                    origPackage = null;
10197                                    continue;
10198                                }
10199                                // TODO: Add case when shared user id is added [b/28144775]
10200                            } else {
10201                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10202                                        + pkg.packageName + " to old name " + origPackage.name);
10203                            }
10204                            break;
10205                        }
10206                    }
10207                }
10208            }
10209
10210            if (mTransferedPackages.contains(pkg.packageName)) {
10211                Slog.w(TAG, "Package " + pkg.packageName
10212                        + " was transferred to another, but its .apk remains");
10213            }
10214
10215            // See comments in nonMutatedPs declaration
10216            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10217                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10218                if (foundPs != null) {
10219                    nonMutatedPs = new PackageSetting(foundPs);
10220                }
10221            }
10222
10223            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
10224                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10225                if (foundPs != null) {
10226                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
10227                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
10228                }
10229            }
10230
10231            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
10232            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
10233                PackageManagerService.reportSettingsProblem(Log.WARN,
10234                        "Package " + pkg.packageName + " shared user changed from "
10235                                + (pkgSetting.sharedUser != null
10236                                        ? pkgSetting.sharedUser.name : "<nothing>")
10237                                + " to "
10238                                + (suid != null ? suid.name : "<nothing>")
10239                                + "; replacing with new");
10240                pkgSetting = null;
10241            }
10242            final PackageSetting oldPkgSetting =
10243                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
10244            final PackageSetting disabledPkgSetting =
10245                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
10246
10247            String[] usesStaticLibraries = null;
10248            if (pkg.usesStaticLibraries != null) {
10249                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10250                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10251            }
10252
10253            if (pkgSetting == null) {
10254                final String parentPackageName = (pkg.parentPackage != null)
10255                        ? pkg.parentPackage.packageName : null;
10256                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10257                // REMOVE SharedUserSetting from method; update in a separate call
10258                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
10259                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
10260                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
10261                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
10262                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
10263                        true /*allowInstall*/, instantApp, parentPackageName,
10264                        pkg.getChildPackageNames(), UserManagerService.getInstance(),
10265                        usesStaticLibraries, pkg.usesStaticLibrariesVersions);
10266                // SIDE EFFECTS; updates system state; move elsewhere
10267                if (origPackage != null) {
10268                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
10269                }
10270                mSettings.addUserToSettingLPw(pkgSetting);
10271            } else {
10272                // REMOVE SharedUserSetting from method; update in a separate call.
10273                //
10274                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10275                // secondaryCpuAbi are not known at this point so we always update them
10276                // to null here, only to reset them at a later point.
10277                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
10278                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
10279                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
10280                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
10281                        UserManagerService.getInstance(), usesStaticLibraries,
10282                        pkg.usesStaticLibrariesVersions);
10283            }
10284            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
10285            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10286
10287            // SIDE EFFECTS; modifies system state; move elsewhere
10288            if (pkgSetting.origPackage != null) {
10289                // If we are first transitioning from an original package,
10290                // fix up the new package's name now.  We need to do this after
10291                // looking up the package under its new name, so getPackageLP
10292                // can take care of fiddling things correctly.
10293                pkg.setPackageName(origPackage.name);
10294
10295                // File a report about this.
10296                String msg = "New package " + pkgSetting.realName
10297                        + " renamed to replace old package " + pkgSetting.name;
10298                reportSettingsProblem(Log.WARN, msg);
10299
10300                // Make a note of it.
10301                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10302                    mTransferedPackages.add(origPackage.name);
10303                }
10304
10305                // No longer need to retain this.
10306                pkgSetting.origPackage = null;
10307            }
10308
10309            // SIDE EFFECTS; modifies system state; move elsewhere
10310            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
10311                // Make a note of it.
10312                mTransferedPackages.add(pkg.packageName);
10313            }
10314
10315            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
10316                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10317            }
10318
10319            if ((scanFlags & SCAN_BOOTING) == 0
10320                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10321                // Check all shared libraries and map to their actual file path.
10322                // We only do this here for apps not on a system dir, because those
10323                // are the only ones that can fail an install due to this.  We
10324                // will take care of the system apps by updating all of their
10325                // library paths after the scan is done. Also during the initial
10326                // scan don't update any libs as we do this wholesale after all
10327                // apps are scanned to avoid dependency based scanning.
10328                updateSharedLibrariesLPr(pkg, null);
10329            }
10330
10331            if (mFoundPolicyFile) {
10332                SELinuxMMAC.assignSeInfoValue(pkg);
10333            }
10334            pkg.applicationInfo.uid = pkgSetting.appId;
10335            pkg.mExtras = pkgSetting;
10336
10337
10338            // Static shared libs have same package with different versions where
10339            // we internally use a synthetic package name to allow multiple versions
10340            // of the same package, therefore we need to compare signatures against
10341            // the package setting for the latest library version.
10342            PackageSetting signatureCheckPs = pkgSetting;
10343            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10344                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10345                if (libraryEntry != null) {
10346                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10347                }
10348            }
10349
10350            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
10351                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
10352                    // We just determined the app is signed correctly, so bring
10353                    // over the latest parsed certs.
10354                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10355                } else {
10356                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10357                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10358                                "Package " + pkg.packageName + " upgrade keys do not match the "
10359                                + "previously installed version");
10360                    } else {
10361                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
10362                        String msg = "System package " + pkg.packageName
10363                                + " signature changed; retaining data.";
10364                        reportSettingsProblem(Log.WARN, msg);
10365                    }
10366                }
10367            } else {
10368                try {
10369                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
10370                    verifySignaturesLP(signatureCheckPs, pkg);
10371                    // We just determined the app is signed correctly, so bring
10372                    // over the latest parsed certs.
10373                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10374                } catch (PackageManagerException e) {
10375                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10376                        throw e;
10377                    }
10378                    // The signature has changed, but this package is in the system
10379                    // image...  let's recover!
10380                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10381                    // However...  if this package is part of a shared user, but it
10382                    // doesn't match the signature of the shared user, let's fail.
10383                    // What this means is that you can't change the signatures
10384                    // associated with an overall shared user, which doesn't seem all
10385                    // that unreasonable.
10386                    if (signatureCheckPs.sharedUser != null) {
10387                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
10388                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
10389                            throw new PackageManagerException(
10390                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10391                                    "Signature mismatch for shared user: "
10392                                            + pkgSetting.sharedUser);
10393                        }
10394                    }
10395                    // File a report about this.
10396                    String msg = "System package " + pkg.packageName
10397                            + " signature changed; retaining data.";
10398                    reportSettingsProblem(Log.WARN, msg);
10399                }
10400            }
10401
10402            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
10403                // This package wants to adopt ownership of permissions from
10404                // another package.
10405                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
10406                    final String origName = pkg.mAdoptPermissions.get(i);
10407                    final PackageSetting orig = mSettings.getPackageLPr(origName);
10408                    if (orig != null) {
10409                        if (verifyPackageUpdateLPr(orig, pkg)) {
10410                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
10411                                    + pkg.packageName);
10412                            // SIDE EFFECTS; updates permissions system state; move elsewhere
10413                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
10414                        }
10415                    }
10416                }
10417            }
10418        }
10419
10420        pkg.applicationInfo.processName = fixProcessName(
10421                pkg.applicationInfo.packageName,
10422                pkg.applicationInfo.processName);
10423
10424        if (pkg != mPlatformPackage) {
10425            // Get all of our default paths setup
10426            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10427        }
10428
10429        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10430
10431        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10432            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
10433                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10434                derivePackageAbi(
10435                        pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir);
10436                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10437
10438                // Some system apps still use directory structure for native libraries
10439                // in which case we might end up not detecting abi solely based on apk
10440                // structure. Try to detect abi based on directory structure.
10441                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
10442                        pkg.applicationInfo.primaryCpuAbi == null) {
10443                    setBundledAppAbisAndRoots(pkg, pkgSetting);
10444                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10445                }
10446            } else {
10447                // This is not a first boot or an upgrade, don't bother deriving the
10448                // ABI during the scan. Instead, trust the value that was stored in the
10449                // package setting.
10450                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
10451                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
10452
10453                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10454
10455                if (DEBUG_ABI_SELECTION) {
10456                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
10457                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
10458                        pkg.applicationInfo.secondaryCpuAbi);
10459                }
10460            }
10461        } else {
10462            if ((scanFlags & SCAN_MOVE) != 0) {
10463                // We haven't run dex-opt for this move (since we've moved the compiled output too)
10464                // but we already have this packages package info in the PackageSetting. We just
10465                // use that and derive the native library path based on the new codepath.
10466                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
10467                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
10468            }
10469
10470            // Set native library paths again. For moves, the path will be updated based on the
10471            // ABIs we've determined above. For non-moves, the path will be updated based on the
10472            // ABIs we determined during compilation, but the path will depend on the final
10473            // package path (after the rename away from the stage path).
10474            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10475        }
10476
10477        // This is a special case for the "system" package, where the ABI is
10478        // dictated by the zygote configuration (and init.rc). We should keep track
10479        // of this ABI so that we can deal with "normal" applications that run under
10480        // the same UID correctly.
10481        if (mPlatformPackage == pkg) {
10482            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
10483                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
10484        }
10485
10486        // If there's a mismatch between the abi-override in the package setting
10487        // and the abiOverride specified for the install. Warn about this because we
10488        // would've already compiled the app without taking the package setting into
10489        // account.
10490        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
10491            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
10492                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
10493                        " for package " + pkg.packageName);
10494            }
10495        }
10496
10497        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10498        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10499        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
10500
10501        // Copy the derived override back to the parsed package, so that we can
10502        // update the package settings accordingly.
10503        pkg.cpuAbiOverride = cpuAbiOverride;
10504
10505        if (DEBUG_ABI_SELECTION) {
10506            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
10507                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
10508                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
10509        }
10510
10511        // Push the derived path down into PackageSettings so we know what to
10512        // clean up at uninstall time.
10513        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
10514
10515        if (DEBUG_ABI_SELECTION) {
10516            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
10517                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
10518                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
10519        }
10520
10521        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
10522        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
10523            // We don't do this here during boot because we can do it all
10524            // at once after scanning all existing packages.
10525            //
10526            // We also do this *before* we perform dexopt on this package, so that
10527            // we can avoid redundant dexopts, and also to make sure we've got the
10528            // code and package path correct.
10529            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
10530        }
10531
10532        if (mFactoryTest && pkg.requestedPermissions.contains(
10533                android.Manifest.permission.FACTORY_TEST)) {
10534            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
10535        }
10536
10537        if (isSystemApp(pkg)) {
10538            pkgSetting.isOrphaned = true;
10539        }
10540
10541        // Take care of first install / last update times.
10542        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
10543        if (currentTime != 0) {
10544            if (pkgSetting.firstInstallTime == 0) {
10545                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
10546            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
10547                pkgSetting.lastUpdateTime = currentTime;
10548            }
10549        } else if (pkgSetting.firstInstallTime == 0) {
10550            // We need *something*.  Take time time stamp of the file.
10551            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
10552        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
10553            if (scanFileTime != pkgSetting.timeStamp) {
10554                // A package on the system image has changed; consider this
10555                // to be an update.
10556                pkgSetting.lastUpdateTime = scanFileTime;
10557            }
10558        }
10559        pkgSetting.setTimeStamp(scanFileTime);
10560
10561        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10562            if (nonMutatedPs != null) {
10563                synchronized (mPackages) {
10564                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
10565                }
10566            }
10567        } else {
10568            final int userId = user == null ? 0 : user.getIdentifier();
10569            // Modify state for the given package setting
10570            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
10571                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
10572            if (pkgSetting.getInstantApp(userId)) {
10573                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
10574            }
10575        }
10576        return pkg;
10577    }
10578
10579    /**
10580     * Applies policy to the parsed package based upon the given policy flags.
10581     * Ensures the package is in a good state.
10582     * <p>
10583     * Implementation detail: This method must NOT have any side effect. It would
10584     * ideally be static, but, it requires locks to read system state.
10585     */
10586    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
10587        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
10588            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
10589            if (pkg.applicationInfo.isDirectBootAware()) {
10590                // we're direct boot aware; set for all components
10591                for (PackageParser.Service s : pkg.services) {
10592                    s.info.encryptionAware = s.info.directBootAware = true;
10593                }
10594                for (PackageParser.Provider p : pkg.providers) {
10595                    p.info.encryptionAware = p.info.directBootAware = true;
10596                }
10597                for (PackageParser.Activity a : pkg.activities) {
10598                    a.info.encryptionAware = a.info.directBootAware = true;
10599                }
10600                for (PackageParser.Activity r : pkg.receivers) {
10601                    r.info.encryptionAware = r.info.directBootAware = true;
10602                }
10603            }
10604        } else {
10605            // Only allow system apps to be flagged as core apps.
10606            pkg.coreApp = false;
10607            // clear flags not applicable to regular apps
10608            pkg.applicationInfo.privateFlags &=
10609                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
10610            pkg.applicationInfo.privateFlags &=
10611                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
10612        }
10613        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
10614
10615        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
10616            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
10617        }
10618
10619        if (!isSystemApp(pkg)) {
10620            // Only system apps can use these features.
10621            pkg.mOriginalPackages = null;
10622            pkg.mRealPackage = null;
10623            pkg.mAdoptPermissions = null;
10624        }
10625    }
10626
10627    /**
10628     * Asserts the parsed package is valid according to the given policy. If the
10629     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
10630     * <p>
10631     * Implementation detail: This method must NOT have any side effects. It would
10632     * ideally be static, but, it requires locks to read system state.
10633     *
10634     * @throws PackageManagerException If the package fails any of the validation checks
10635     */
10636    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
10637            throws PackageManagerException {
10638        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
10639            assertCodePolicy(pkg);
10640        }
10641
10642        if (pkg.applicationInfo.getCodePath() == null ||
10643                pkg.applicationInfo.getResourcePath() == null) {
10644            // Bail out. The resource and code paths haven't been set.
10645            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10646                    "Code and resource paths haven't been set correctly");
10647        }
10648
10649        // Make sure we're not adding any bogus keyset info
10650        KeySetManagerService ksms = mSettings.mKeySetManagerService;
10651        ksms.assertScannedPackageValid(pkg);
10652
10653        synchronized (mPackages) {
10654            // The special "android" package can only be defined once
10655            if (pkg.packageName.equals("android")) {
10656                if (mAndroidApplication != null) {
10657                    Slog.w(TAG, "*************************************************");
10658                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
10659                    Slog.w(TAG, " codePath=" + pkg.codePath);
10660                    Slog.w(TAG, "*************************************************");
10661                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10662                            "Core android package being redefined.  Skipping.");
10663                }
10664            }
10665
10666            // A package name must be unique; don't allow duplicates
10667            if (mPackages.containsKey(pkg.packageName)) {
10668                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10669                        "Application package " + pkg.packageName
10670                        + " already installed.  Skipping duplicate.");
10671            }
10672
10673            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10674                // Static libs have a synthetic package name containing the version
10675                // but we still want the base name to be unique.
10676                if (mPackages.containsKey(pkg.manifestPackageName)) {
10677                    throw new PackageManagerException(
10678                            "Duplicate static shared lib provider package");
10679                }
10680
10681                // Static shared libraries should have at least O target SDK
10682                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
10683                    throw new PackageManagerException(
10684                            "Packages declaring static-shared libs must target O SDK or higher");
10685                }
10686
10687                // Package declaring static a shared lib cannot be instant apps
10688                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10689                    throw new PackageManagerException(
10690                            "Packages declaring static-shared libs cannot be instant apps");
10691                }
10692
10693                // Package declaring static a shared lib cannot be renamed since the package
10694                // name is synthetic and apps can't code around package manager internals.
10695                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
10696                    throw new PackageManagerException(
10697                            "Packages declaring static-shared libs cannot be renamed");
10698                }
10699
10700                // Package declaring static a shared lib cannot declare child packages
10701                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
10702                    throw new PackageManagerException(
10703                            "Packages declaring static-shared libs cannot have child packages");
10704                }
10705
10706                // Package declaring static a shared lib cannot declare dynamic libs
10707                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
10708                    throw new PackageManagerException(
10709                            "Packages declaring static-shared libs cannot declare dynamic libs");
10710                }
10711
10712                // Package declaring static a shared lib cannot declare shared users
10713                if (pkg.mSharedUserId != null) {
10714                    throw new PackageManagerException(
10715                            "Packages declaring static-shared libs cannot declare shared users");
10716                }
10717
10718                // Static shared libs cannot declare activities
10719                if (!pkg.activities.isEmpty()) {
10720                    throw new PackageManagerException(
10721                            "Static shared libs cannot declare activities");
10722                }
10723
10724                // Static shared libs cannot declare services
10725                if (!pkg.services.isEmpty()) {
10726                    throw new PackageManagerException(
10727                            "Static shared libs cannot declare services");
10728                }
10729
10730                // Static shared libs cannot declare providers
10731                if (!pkg.providers.isEmpty()) {
10732                    throw new PackageManagerException(
10733                            "Static shared libs cannot declare content providers");
10734                }
10735
10736                // Static shared libs cannot declare receivers
10737                if (!pkg.receivers.isEmpty()) {
10738                    throw new PackageManagerException(
10739                            "Static shared libs cannot declare broadcast receivers");
10740                }
10741
10742                // Static shared libs cannot declare permission groups
10743                if (!pkg.permissionGroups.isEmpty()) {
10744                    throw new PackageManagerException(
10745                            "Static shared libs cannot declare permission groups");
10746                }
10747
10748                // Static shared libs cannot declare permissions
10749                if (!pkg.permissions.isEmpty()) {
10750                    throw new PackageManagerException(
10751                            "Static shared libs cannot declare permissions");
10752                }
10753
10754                // Static shared libs cannot declare protected broadcasts
10755                if (pkg.protectedBroadcasts != null) {
10756                    throw new PackageManagerException(
10757                            "Static shared libs cannot declare protected broadcasts");
10758                }
10759
10760                // Static shared libs cannot be overlay targets
10761                if (pkg.mOverlayTarget != null) {
10762                    throw new PackageManagerException(
10763                            "Static shared libs cannot be overlay targets");
10764                }
10765
10766                // The version codes must be ordered as lib versions
10767                int minVersionCode = Integer.MIN_VALUE;
10768                int maxVersionCode = Integer.MAX_VALUE;
10769
10770                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10771                        pkg.staticSharedLibName);
10772                if (versionedLib != null) {
10773                    final int versionCount = versionedLib.size();
10774                    for (int i = 0; i < versionCount; i++) {
10775                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
10776                        final int libVersionCode = libInfo.getDeclaringPackage()
10777                                .getVersionCode();
10778                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
10779                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
10780                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
10781                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
10782                        } else {
10783                            minVersionCode = maxVersionCode = libVersionCode;
10784                            break;
10785                        }
10786                    }
10787                }
10788                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
10789                    throw new PackageManagerException("Static shared"
10790                            + " lib version codes must be ordered as lib versions");
10791                }
10792            }
10793
10794            // Only privileged apps and updated privileged apps can add child packages.
10795            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
10796                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
10797                    throw new PackageManagerException("Only privileged apps can add child "
10798                            + "packages. Ignoring package " + pkg.packageName);
10799                }
10800                final int childCount = pkg.childPackages.size();
10801                for (int i = 0; i < childCount; i++) {
10802                    PackageParser.Package childPkg = pkg.childPackages.get(i);
10803                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
10804                            childPkg.packageName)) {
10805                        throw new PackageManagerException("Can't override child of "
10806                                + "another disabled app. Ignoring package " + pkg.packageName);
10807                    }
10808                }
10809            }
10810
10811            // If we're only installing presumed-existing packages, require that the
10812            // scanned APK is both already known and at the path previously established
10813            // for it.  Previously unknown packages we pick up normally, but if we have an
10814            // a priori expectation about this package's install presence, enforce it.
10815            // With a singular exception for new system packages. When an OTA contains
10816            // a new system package, we allow the codepath to change from a system location
10817            // to the user-installed location. If we don't allow this change, any newer,
10818            // user-installed version of the application will be ignored.
10819            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
10820                if (mExpectingBetter.containsKey(pkg.packageName)) {
10821                    logCriticalInfo(Log.WARN,
10822                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
10823                } else {
10824                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
10825                    if (known != null) {
10826                        if (DEBUG_PACKAGE_SCANNING) {
10827                            Log.d(TAG, "Examining " + pkg.codePath
10828                                    + " and requiring known paths " + known.codePathString
10829                                    + " & " + known.resourcePathString);
10830                        }
10831                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
10832                                || !pkg.applicationInfo.getResourcePath().equals(
10833                                        known.resourcePathString)) {
10834                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
10835                                    "Application package " + pkg.packageName
10836                                    + " found at " + pkg.applicationInfo.getCodePath()
10837                                    + " but expected at " + known.codePathString
10838                                    + "; ignoring.");
10839                        }
10840                    }
10841                }
10842            }
10843
10844            // Verify that this new package doesn't have any content providers
10845            // that conflict with existing packages.  Only do this if the
10846            // package isn't already installed, since we don't want to break
10847            // things that are installed.
10848            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
10849                final int N = pkg.providers.size();
10850                int i;
10851                for (i=0; i<N; i++) {
10852                    PackageParser.Provider p = pkg.providers.get(i);
10853                    if (p.info.authority != null) {
10854                        String names[] = p.info.authority.split(";");
10855                        for (int j = 0; j < names.length; j++) {
10856                            if (mProvidersByAuthority.containsKey(names[j])) {
10857                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10858                                final String otherPackageName =
10859                                        ((other != null && other.getComponentName() != null) ?
10860                                                other.getComponentName().getPackageName() : "?");
10861                                throw new PackageManagerException(
10862                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
10863                                        "Can't install because provider name " + names[j]
10864                                                + " (in package " + pkg.applicationInfo.packageName
10865                                                + ") is already used by " + otherPackageName);
10866                            }
10867                        }
10868                    }
10869                }
10870            }
10871        }
10872    }
10873
10874    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
10875            int type, String declaringPackageName, int declaringVersionCode) {
10876        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10877        if (versionedLib == null) {
10878            versionedLib = new SparseArray<>();
10879            mSharedLibraries.put(name, versionedLib);
10880            if (type == SharedLibraryInfo.TYPE_STATIC) {
10881                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
10882            }
10883        } else if (versionedLib.indexOfKey(version) >= 0) {
10884            return false;
10885        }
10886        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
10887                version, type, declaringPackageName, declaringVersionCode);
10888        versionedLib.put(version, libEntry);
10889        return true;
10890    }
10891
10892    private boolean removeSharedLibraryLPw(String name, int version) {
10893        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10894        if (versionedLib == null) {
10895            return false;
10896        }
10897        final int libIdx = versionedLib.indexOfKey(version);
10898        if (libIdx < 0) {
10899            return false;
10900        }
10901        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
10902        versionedLib.remove(version);
10903        if (versionedLib.size() <= 0) {
10904            mSharedLibraries.remove(name);
10905            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
10906                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
10907                        .getPackageName());
10908            }
10909        }
10910        return true;
10911    }
10912
10913    /**
10914     * Adds a scanned package to the system. When this method is finished, the package will
10915     * be available for query, resolution, etc...
10916     */
10917    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
10918            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
10919        final String pkgName = pkg.packageName;
10920        if (mCustomResolverComponentName != null &&
10921                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
10922            setUpCustomResolverActivity(pkg);
10923        }
10924
10925        if (pkg.packageName.equals("android")) {
10926            synchronized (mPackages) {
10927                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10928                    // Set up information for our fall-back user intent resolution activity.
10929                    mPlatformPackage = pkg;
10930                    pkg.mVersionCode = mSdkVersion;
10931                    mAndroidApplication = pkg.applicationInfo;
10932                    if (!mResolverReplaced) {
10933                        mResolveActivity.applicationInfo = mAndroidApplication;
10934                        mResolveActivity.name = ResolverActivity.class.getName();
10935                        mResolveActivity.packageName = mAndroidApplication.packageName;
10936                        mResolveActivity.processName = "system:ui";
10937                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10938                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
10939                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
10940                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
10941                        mResolveActivity.exported = true;
10942                        mResolveActivity.enabled = true;
10943                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
10944                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
10945                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
10946                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
10947                                | ActivityInfo.CONFIG_ORIENTATION
10948                                | ActivityInfo.CONFIG_KEYBOARD
10949                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
10950                        mResolveInfo.activityInfo = mResolveActivity;
10951                        mResolveInfo.priority = 0;
10952                        mResolveInfo.preferredOrder = 0;
10953                        mResolveInfo.match = 0;
10954                        mResolveComponentName = new ComponentName(
10955                                mAndroidApplication.packageName, mResolveActivity.name);
10956                    }
10957                }
10958            }
10959        }
10960
10961        ArrayList<PackageParser.Package> clientLibPkgs = null;
10962        // writer
10963        synchronized (mPackages) {
10964            boolean hasStaticSharedLibs = false;
10965
10966            // Any app can add new static shared libraries
10967            if (pkg.staticSharedLibName != null) {
10968                // Static shared libs don't allow renaming as they have synthetic package
10969                // names to allow install of multiple versions, so use name from manifest.
10970                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
10971                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
10972                        pkg.manifestPackageName, pkg.mVersionCode)) {
10973                    hasStaticSharedLibs = true;
10974                } else {
10975                    Slog.w(TAG, "Package " + pkg.packageName + " library "
10976                                + pkg.staticSharedLibName + " already exists; skipping");
10977                }
10978                // Static shared libs cannot be updated once installed since they
10979                // use synthetic package name which includes the version code, so
10980                // not need to update other packages's shared lib dependencies.
10981            }
10982
10983            if (!hasStaticSharedLibs
10984                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10985                // Only system apps can add new dynamic shared libraries.
10986                if (pkg.libraryNames != null) {
10987                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
10988                        String name = pkg.libraryNames.get(i);
10989                        boolean allowed = false;
10990                        if (pkg.isUpdatedSystemApp()) {
10991                            // New library entries can only be added through the
10992                            // system image.  This is important to get rid of a lot
10993                            // of nasty edge cases: for example if we allowed a non-
10994                            // system update of the app to add a library, then uninstalling
10995                            // the update would make the library go away, and assumptions
10996                            // we made such as through app install filtering would now
10997                            // have allowed apps on the device which aren't compatible
10998                            // with it.  Better to just have the restriction here, be
10999                            // conservative, and create many fewer cases that can negatively
11000                            // impact the user experience.
11001                            final PackageSetting sysPs = mSettings
11002                                    .getDisabledSystemPkgLPr(pkg.packageName);
11003                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
11004                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
11005                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
11006                                        allowed = true;
11007                                        break;
11008                                    }
11009                                }
11010                            }
11011                        } else {
11012                            allowed = true;
11013                        }
11014                        if (allowed) {
11015                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
11016                                    SharedLibraryInfo.VERSION_UNDEFINED,
11017                                    SharedLibraryInfo.TYPE_DYNAMIC,
11018                                    pkg.packageName, pkg.mVersionCode)) {
11019                                Slog.w(TAG, "Package " + pkg.packageName + " library "
11020                                        + name + " already exists; skipping");
11021                            }
11022                        } else {
11023                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
11024                                    + name + " that is not declared on system image; skipping");
11025                        }
11026                    }
11027
11028                    if ((scanFlags & SCAN_BOOTING) == 0) {
11029                        // If we are not booting, we need to update any applications
11030                        // that are clients of our shared library.  If we are booting,
11031                        // this will all be done once the scan is complete.
11032                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
11033                    }
11034                }
11035            }
11036        }
11037
11038        if ((scanFlags & SCAN_BOOTING) != 0) {
11039            // No apps can run during boot scan, so they don't need to be frozen
11040        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
11041            // Caller asked to not kill app, so it's probably not frozen
11042        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
11043            // Caller asked us to ignore frozen check for some reason; they
11044            // probably didn't know the package name
11045        } else {
11046            // We're doing major surgery on this package, so it better be frozen
11047            // right now to keep it from launching
11048            checkPackageFrozen(pkgName);
11049        }
11050
11051        // Also need to kill any apps that are dependent on the library.
11052        if (clientLibPkgs != null) {
11053            for (int i=0; i<clientLibPkgs.size(); i++) {
11054                PackageParser.Package clientPkg = clientLibPkgs.get(i);
11055                killApplication(clientPkg.applicationInfo.packageName,
11056                        clientPkg.applicationInfo.uid, "update lib");
11057            }
11058        }
11059
11060        // writer
11061        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
11062
11063        synchronized (mPackages) {
11064            // We don't expect installation to fail beyond this point
11065
11066            // Add the new setting to mSettings
11067            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
11068            // Add the new setting to mPackages
11069            mPackages.put(pkg.applicationInfo.packageName, pkg);
11070            // Make sure we don't accidentally delete its data.
11071            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
11072            while (iter.hasNext()) {
11073                PackageCleanItem item = iter.next();
11074                if (pkgName.equals(item.packageName)) {
11075                    iter.remove();
11076                }
11077            }
11078
11079            // Add the package's KeySets to the global KeySetManagerService
11080            KeySetManagerService ksms = mSettings.mKeySetManagerService;
11081            ksms.addScannedPackageLPw(pkg);
11082
11083            int N = pkg.providers.size();
11084            StringBuilder r = null;
11085            int i;
11086            for (i=0; i<N; i++) {
11087                PackageParser.Provider p = pkg.providers.get(i);
11088                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11089                        p.info.processName);
11090                mProviders.addProvider(p);
11091                p.syncable = p.info.isSyncable;
11092                if (p.info.authority != null) {
11093                    String names[] = p.info.authority.split(";");
11094                    p.info.authority = null;
11095                    for (int j = 0; j < names.length; j++) {
11096                        if (j == 1 && p.syncable) {
11097                            // We only want the first authority for a provider to possibly be
11098                            // syncable, so if we already added this provider using a different
11099                            // authority clear the syncable flag. We copy the provider before
11100                            // changing it because the mProviders object contains a reference
11101                            // to a provider that we don't want to change.
11102                            // Only do this for the second authority since the resulting provider
11103                            // object can be the same for all future authorities for this provider.
11104                            p = new PackageParser.Provider(p);
11105                            p.syncable = false;
11106                        }
11107                        if (!mProvidersByAuthority.containsKey(names[j])) {
11108                            mProvidersByAuthority.put(names[j], p);
11109                            if (p.info.authority == null) {
11110                                p.info.authority = names[j];
11111                            } else {
11112                                p.info.authority = p.info.authority + ";" + names[j];
11113                            }
11114                            if (DEBUG_PACKAGE_SCANNING) {
11115                                if (chatty)
11116                                    Log.d(TAG, "Registered content provider: " + names[j]
11117                                            + ", className = " + p.info.name + ", isSyncable = "
11118                                            + p.info.isSyncable);
11119                            }
11120                        } else {
11121                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11122                            Slog.w(TAG, "Skipping provider name " + names[j] +
11123                                    " (in package " + pkg.applicationInfo.packageName +
11124                                    "): name already used by "
11125                                    + ((other != null && other.getComponentName() != null)
11126                                            ? other.getComponentName().getPackageName() : "?"));
11127                        }
11128                    }
11129                }
11130                if (chatty) {
11131                    if (r == null) {
11132                        r = new StringBuilder(256);
11133                    } else {
11134                        r.append(' ');
11135                    }
11136                    r.append(p.info.name);
11137                }
11138            }
11139            if (r != null) {
11140                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
11141            }
11142
11143            N = pkg.services.size();
11144            r = null;
11145            for (i=0; i<N; i++) {
11146                PackageParser.Service s = pkg.services.get(i);
11147                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11148                        s.info.processName);
11149                mServices.addService(s);
11150                if (chatty) {
11151                    if (r == null) {
11152                        r = new StringBuilder(256);
11153                    } else {
11154                        r.append(' ');
11155                    }
11156                    r.append(s.info.name);
11157                }
11158            }
11159            if (r != null) {
11160                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
11161            }
11162
11163            N = pkg.receivers.size();
11164            r = null;
11165            for (i=0; i<N; i++) {
11166                PackageParser.Activity a = pkg.receivers.get(i);
11167                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11168                        a.info.processName);
11169                mReceivers.addActivity(a, "receiver");
11170                if (chatty) {
11171                    if (r == null) {
11172                        r = new StringBuilder(256);
11173                    } else {
11174                        r.append(' ');
11175                    }
11176                    r.append(a.info.name);
11177                }
11178            }
11179            if (r != null) {
11180                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11181            }
11182
11183            N = pkg.activities.size();
11184            r = null;
11185            for (i=0; i<N; i++) {
11186                PackageParser.Activity a = pkg.activities.get(i);
11187                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11188                        a.info.processName);
11189                mActivities.addActivity(a, "activity");
11190                if (chatty) {
11191                    if (r == null) {
11192                        r = new StringBuilder(256);
11193                    } else {
11194                        r.append(' ');
11195                    }
11196                    r.append(a.info.name);
11197                }
11198            }
11199            if (r != null) {
11200                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11201            }
11202
11203            N = pkg.permissionGroups.size();
11204            r = null;
11205            for (i=0; i<N; i++) {
11206                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
11207                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
11208                final String curPackageName = cur == null ? null : cur.info.packageName;
11209                // Dont allow ephemeral apps to define new permission groups.
11210                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11211                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11212                            + pg.info.packageName
11213                            + " ignored: instant apps cannot define new permission groups.");
11214                    continue;
11215                }
11216                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
11217                if (cur == null || isPackageUpdate) {
11218                    mPermissionGroups.put(pg.info.name, pg);
11219                    if (chatty) {
11220                        if (r == null) {
11221                            r = new StringBuilder(256);
11222                        } else {
11223                            r.append(' ');
11224                        }
11225                        if (isPackageUpdate) {
11226                            r.append("UPD:");
11227                        }
11228                        r.append(pg.info.name);
11229                    }
11230                } else {
11231                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11232                            + pg.info.packageName + " ignored: original from "
11233                            + cur.info.packageName);
11234                    if (chatty) {
11235                        if (r == null) {
11236                            r = new StringBuilder(256);
11237                        } else {
11238                            r.append(' ');
11239                        }
11240                        r.append("DUP:");
11241                        r.append(pg.info.name);
11242                    }
11243                }
11244            }
11245            if (r != null) {
11246                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
11247            }
11248
11249            N = pkg.permissions.size();
11250            r = null;
11251            for (i=0; i<N; i++) {
11252                PackageParser.Permission p = pkg.permissions.get(i);
11253
11254                // Dont allow ephemeral apps to define new permissions.
11255                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11256                    Slog.w(TAG, "Permission " + p.info.name + " from package "
11257                            + p.info.packageName
11258                            + " ignored: instant apps cannot define new permissions.");
11259                    continue;
11260                }
11261
11262                // Assume by default that we did not install this permission into the system.
11263                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
11264
11265                // Now that permission groups have a special meaning, we ignore permission
11266                // groups for legacy apps to prevent unexpected behavior. In particular,
11267                // permissions for one app being granted to someone just because they happen
11268                // to be in a group defined by another app (before this had no implications).
11269                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
11270                    p.group = mPermissionGroups.get(p.info.group);
11271                    // Warn for a permission in an unknown group.
11272                    if (DEBUG_PERMISSIONS && p.info.group != null && p.group == null) {
11273                        Slog.i(TAG, "Permission " + p.info.name + " from package "
11274                                + p.info.packageName + " in an unknown group " + p.info.group);
11275                    }
11276                }
11277
11278                ArrayMap<String, BasePermission> permissionMap =
11279                        p.tree ? mSettings.mPermissionTrees
11280                                : mSettings.mPermissions;
11281                BasePermission bp = permissionMap.get(p.info.name);
11282
11283                // Allow system apps to redefine non-system permissions
11284                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
11285                    final boolean currentOwnerIsSystem = (bp.perm != null
11286                            && isSystemApp(bp.perm.owner));
11287                    if (isSystemApp(p.owner)) {
11288                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
11289                            // It's a built-in permission and no owner, take ownership now
11290                            bp.packageSetting = pkgSetting;
11291                            bp.perm = p;
11292                            bp.uid = pkg.applicationInfo.uid;
11293                            bp.sourcePackage = p.info.packageName;
11294                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11295                        } else if (!currentOwnerIsSystem) {
11296                            String msg = "New decl " + p.owner + " of permission  "
11297                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
11298                            reportSettingsProblem(Log.WARN, msg);
11299                            bp = null;
11300                        }
11301                    }
11302                }
11303
11304                if (bp == null) {
11305                    bp = new BasePermission(p.info.name, p.info.packageName,
11306                            BasePermission.TYPE_NORMAL);
11307                    permissionMap.put(p.info.name, bp);
11308                }
11309
11310                if (bp.perm == null) {
11311                    if (bp.sourcePackage == null
11312                            || bp.sourcePackage.equals(p.info.packageName)) {
11313                        BasePermission tree = findPermissionTreeLP(p.info.name);
11314                        if (tree == null
11315                                || tree.sourcePackage.equals(p.info.packageName)) {
11316                            bp.packageSetting = pkgSetting;
11317                            bp.perm = p;
11318                            bp.uid = pkg.applicationInfo.uid;
11319                            bp.sourcePackage = p.info.packageName;
11320                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11321                            if (chatty) {
11322                                if (r == null) {
11323                                    r = new StringBuilder(256);
11324                                } else {
11325                                    r.append(' ');
11326                                }
11327                                r.append(p.info.name);
11328                            }
11329                        } else {
11330                            Slog.w(TAG, "Permission " + p.info.name + " from package "
11331                                    + p.info.packageName + " ignored: base tree "
11332                                    + tree.name + " is from package "
11333                                    + tree.sourcePackage);
11334                        }
11335                    } else {
11336                        Slog.w(TAG, "Permission " + p.info.name + " from package "
11337                                + p.info.packageName + " ignored: original from "
11338                                + bp.sourcePackage);
11339                    }
11340                } else if (chatty) {
11341                    if (r == null) {
11342                        r = new StringBuilder(256);
11343                    } else {
11344                        r.append(' ');
11345                    }
11346                    r.append("DUP:");
11347                    r.append(p.info.name);
11348                }
11349                if (bp.perm == p) {
11350                    bp.protectionLevel = p.info.protectionLevel;
11351                }
11352            }
11353
11354            if (r != null) {
11355                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
11356            }
11357
11358            N = pkg.instrumentation.size();
11359            r = null;
11360            for (i=0; i<N; i++) {
11361                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11362                a.info.packageName = pkg.applicationInfo.packageName;
11363                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11364                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11365                a.info.splitNames = pkg.splitNames;
11366                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11367                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11368                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11369                a.info.dataDir = pkg.applicationInfo.dataDir;
11370                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11371                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11372                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11373                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11374                mInstrumentation.put(a.getComponentName(), a);
11375                if (chatty) {
11376                    if (r == null) {
11377                        r = new StringBuilder(256);
11378                    } else {
11379                        r.append(' ');
11380                    }
11381                    r.append(a.info.name);
11382                }
11383            }
11384            if (r != null) {
11385                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
11386            }
11387
11388            if (pkg.protectedBroadcasts != null) {
11389                N = pkg.protectedBroadcasts.size();
11390                for (i=0; i<N; i++) {
11391                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11392                }
11393            }
11394        }
11395
11396        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11397    }
11398
11399    /**
11400     * Derive the ABI of a non-system package located at {@code scanFile}. This information
11401     * is derived purely on the basis of the contents of {@code scanFile} and
11402     * {@code cpuAbiOverride}.
11403     *
11404     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
11405     */
11406    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
11407                                 String cpuAbiOverride, boolean extractLibs,
11408                                 File appLib32InstallDir)
11409            throws PackageManagerException {
11410        // Give ourselves some initial paths; we'll come back for another
11411        // pass once we've determined ABI below.
11412        setNativeLibraryPaths(pkg, appLib32InstallDir);
11413
11414        // We would never need to extract libs for forward-locked and external packages,
11415        // since the container service will do it for us. We shouldn't attempt to
11416        // extract libs from system app when it was not updated.
11417        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
11418                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
11419            extractLibs = false;
11420        }
11421
11422        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
11423        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
11424
11425        NativeLibraryHelper.Handle handle = null;
11426        try {
11427            handle = NativeLibraryHelper.Handle.create(pkg);
11428            // TODO(multiArch): This can be null for apps that didn't go through the
11429            // usual installation process. We can calculate it again, like we
11430            // do during install time.
11431            //
11432            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
11433            // unnecessary.
11434            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
11435
11436            // Null out the abis so that they can be recalculated.
11437            pkg.applicationInfo.primaryCpuAbi = null;
11438            pkg.applicationInfo.secondaryCpuAbi = null;
11439            if (isMultiArch(pkg.applicationInfo)) {
11440                // Warn if we've set an abiOverride for multi-lib packages..
11441                // By definition, we need to copy both 32 and 64 bit libraries for
11442                // such packages.
11443                if (pkg.cpuAbiOverride != null
11444                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
11445                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
11446                }
11447
11448                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
11449                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
11450                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
11451                    if (extractLibs) {
11452                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11453                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11454                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
11455                                useIsaSpecificSubdirs);
11456                    } else {
11457                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11458                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
11459                    }
11460                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11461                }
11462
11463                maybeThrowExceptionForMultiArchCopy(
11464                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
11465
11466                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
11467                    if (extractLibs) {
11468                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11469                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11470                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
11471                                useIsaSpecificSubdirs);
11472                    } else {
11473                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11474                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
11475                    }
11476                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11477                }
11478
11479                maybeThrowExceptionForMultiArchCopy(
11480                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
11481
11482                if (abi64 >= 0) {
11483                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
11484                }
11485
11486                if (abi32 >= 0) {
11487                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
11488                    if (abi64 >= 0) {
11489                        if (pkg.use32bitAbi) {
11490                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11491                            pkg.applicationInfo.primaryCpuAbi = abi;
11492                        } else {
11493                            pkg.applicationInfo.secondaryCpuAbi = abi;
11494                        }
11495                    } else {
11496                        pkg.applicationInfo.primaryCpuAbi = abi;
11497                    }
11498                }
11499
11500            } else {
11501                String[] abiList = (cpuAbiOverride != null) ?
11502                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
11503
11504                // Enable gross and lame hacks for apps that are built with old
11505                // SDK tools. We must scan their APKs for renderscript bitcode and
11506                // not launch them if it's present. Don't bother checking on devices
11507                // that don't have 64 bit support.
11508                boolean needsRenderScriptOverride = false;
11509                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
11510                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
11511                    abiList = Build.SUPPORTED_32_BIT_ABIS;
11512                    needsRenderScriptOverride = true;
11513                }
11514
11515                final int copyRet;
11516                if (extractLibs) {
11517                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11518                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11519                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
11520                } else {
11521                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11522                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
11523                }
11524                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11525
11526                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
11527                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11528                            "Error unpackaging native libs for app, errorCode=" + copyRet);
11529                }
11530
11531                if (copyRet >= 0) {
11532                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
11533                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
11534                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
11535                } else if (needsRenderScriptOverride) {
11536                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
11537                }
11538            }
11539        } catch (IOException ioe) {
11540            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
11541        } finally {
11542            IoUtils.closeQuietly(handle);
11543        }
11544
11545        // Now that we've calculated the ABIs and determined if it's an internal app,
11546        // we will go ahead and populate the nativeLibraryPath.
11547        setNativeLibraryPaths(pkg, appLib32InstallDir);
11548    }
11549
11550    /**
11551     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
11552     * i.e, so that all packages can be run inside a single process if required.
11553     *
11554     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
11555     * this function will either try and make the ABI for all packages in {@code packagesForUser}
11556     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
11557     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
11558     * updating a package that belongs to a shared user.
11559     *
11560     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
11561     * adds unnecessary complexity.
11562     */
11563    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
11564            PackageParser.Package scannedPackage) {
11565        String requiredInstructionSet = null;
11566        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
11567            requiredInstructionSet = VMRuntime.getInstructionSet(
11568                     scannedPackage.applicationInfo.primaryCpuAbi);
11569        }
11570
11571        PackageSetting requirer = null;
11572        for (PackageSetting ps : packagesForUser) {
11573            // If packagesForUser contains scannedPackage, we skip it. This will happen
11574            // when scannedPackage is an update of an existing package. Without this check,
11575            // we will never be able to change the ABI of any package belonging to a shared
11576            // user, even if it's compatible with other packages.
11577            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11578                if (ps.primaryCpuAbiString == null) {
11579                    continue;
11580                }
11581
11582                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
11583                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
11584                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
11585                    // this but there's not much we can do.
11586                    String errorMessage = "Instruction set mismatch, "
11587                            + ((requirer == null) ? "[caller]" : requirer)
11588                            + " requires " + requiredInstructionSet + " whereas " + ps
11589                            + " requires " + instructionSet;
11590                    Slog.w(TAG, errorMessage);
11591                }
11592
11593                if (requiredInstructionSet == null) {
11594                    requiredInstructionSet = instructionSet;
11595                    requirer = ps;
11596                }
11597            }
11598        }
11599
11600        if (requiredInstructionSet != null) {
11601            String adjustedAbi;
11602            if (requirer != null) {
11603                // requirer != null implies that either scannedPackage was null or that scannedPackage
11604                // did not require an ABI, in which case we have to adjust scannedPackage to match
11605                // the ABI of the set (which is the same as requirer's ABI)
11606                adjustedAbi = requirer.primaryCpuAbiString;
11607                if (scannedPackage != null) {
11608                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
11609                }
11610            } else {
11611                // requirer == null implies that we're updating all ABIs in the set to
11612                // match scannedPackage.
11613                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
11614            }
11615
11616            for (PackageSetting ps : packagesForUser) {
11617                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11618                    if (ps.primaryCpuAbiString != null) {
11619                        continue;
11620                    }
11621
11622                    ps.primaryCpuAbiString = adjustedAbi;
11623                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
11624                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
11625                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
11626                        if (DEBUG_ABI_SELECTION) {
11627                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
11628                                    + " (requirer="
11629                                    + (requirer != null ? requirer.pkg : "null")
11630                                    + ", scannedPackage="
11631                                    + (scannedPackage != null ? scannedPackage : "null")
11632                                    + ")");
11633                        }
11634                        try {
11635                            mInstaller.rmdex(ps.codePathString,
11636                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
11637                        } catch (InstallerException ignored) {
11638                        }
11639                    }
11640                }
11641            }
11642        }
11643    }
11644
11645    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
11646        synchronized (mPackages) {
11647            mResolverReplaced = true;
11648            // Set up information for custom user intent resolution activity.
11649            mResolveActivity.applicationInfo = pkg.applicationInfo;
11650            mResolveActivity.name = mCustomResolverComponentName.getClassName();
11651            mResolveActivity.packageName = pkg.applicationInfo.packageName;
11652            mResolveActivity.processName = pkg.applicationInfo.packageName;
11653            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11654            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
11655                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11656            mResolveActivity.theme = 0;
11657            mResolveActivity.exported = true;
11658            mResolveActivity.enabled = true;
11659            mResolveInfo.activityInfo = mResolveActivity;
11660            mResolveInfo.priority = 0;
11661            mResolveInfo.preferredOrder = 0;
11662            mResolveInfo.match = 0;
11663            mResolveComponentName = mCustomResolverComponentName;
11664            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
11665                    mResolveComponentName);
11666        }
11667    }
11668
11669    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
11670        if (installerActivity == null) {
11671            if (DEBUG_EPHEMERAL) {
11672                Slog.d(TAG, "Clear ephemeral installer activity");
11673            }
11674            mInstantAppInstallerActivity = null;
11675            return;
11676        }
11677
11678        if (DEBUG_EPHEMERAL) {
11679            Slog.d(TAG, "Set ephemeral installer activity: "
11680                    + installerActivity.getComponentName());
11681        }
11682        // Set up information for ephemeral installer activity
11683        mInstantAppInstallerActivity = installerActivity;
11684        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
11685                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11686        mInstantAppInstallerActivity.exported = true;
11687        mInstantAppInstallerActivity.enabled = true;
11688        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
11689        mInstantAppInstallerInfo.priority = 0;
11690        mInstantAppInstallerInfo.preferredOrder = 1;
11691        mInstantAppInstallerInfo.isDefault = true;
11692        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
11693                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
11694    }
11695
11696    private static String calculateBundledApkRoot(final String codePathString) {
11697        final File codePath = new File(codePathString);
11698        final File codeRoot;
11699        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
11700            codeRoot = Environment.getRootDirectory();
11701        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
11702            codeRoot = Environment.getOemDirectory();
11703        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
11704            codeRoot = Environment.getVendorDirectory();
11705        } else {
11706            // Unrecognized code path; take its top real segment as the apk root:
11707            // e.g. /something/app/blah.apk => /something
11708            try {
11709                File f = codePath.getCanonicalFile();
11710                File parent = f.getParentFile();    // non-null because codePath is a file
11711                File tmp;
11712                while ((tmp = parent.getParentFile()) != null) {
11713                    f = parent;
11714                    parent = tmp;
11715                }
11716                codeRoot = f;
11717                Slog.w(TAG, "Unrecognized code path "
11718                        + codePath + " - using " + codeRoot);
11719            } catch (IOException e) {
11720                // Can't canonicalize the code path -- shenanigans?
11721                Slog.w(TAG, "Can't canonicalize code path " + codePath);
11722                return Environment.getRootDirectory().getPath();
11723            }
11724        }
11725        return codeRoot.getPath();
11726    }
11727
11728    /**
11729     * Derive and set the location of native libraries for the given package,
11730     * which varies depending on where and how the package was installed.
11731     */
11732    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
11733        final ApplicationInfo info = pkg.applicationInfo;
11734        final String codePath = pkg.codePath;
11735        final File codeFile = new File(codePath);
11736        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
11737        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
11738
11739        info.nativeLibraryRootDir = null;
11740        info.nativeLibraryRootRequiresIsa = false;
11741        info.nativeLibraryDir = null;
11742        info.secondaryNativeLibraryDir = null;
11743
11744        if (isApkFile(codeFile)) {
11745            // Monolithic install
11746            if (bundledApp) {
11747                // If "/system/lib64/apkname" exists, assume that is the per-package
11748                // native library directory to use; otherwise use "/system/lib/apkname".
11749                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
11750                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
11751                        getPrimaryInstructionSet(info));
11752
11753                // This is a bundled system app so choose the path based on the ABI.
11754                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
11755                // is just the default path.
11756                final String apkName = deriveCodePathName(codePath);
11757                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
11758                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
11759                        apkName).getAbsolutePath();
11760
11761                if (info.secondaryCpuAbi != null) {
11762                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
11763                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
11764                            secondaryLibDir, apkName).getAbsolutePath();
11765                }
11766            } else if (asecApp) {
11767                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
11768                        .getAbsolutePath();
11769            } else {
11770                final String apkName = deriveCodePathName(codePath);
11771                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
11772                        .getAbsolutePath();
11773            }
11774
11775            info.nativeLibraryRootRequiresIsa = false;
11776            info.nativeLibraryDir = info.nativeLibraryRootDir;
11777        } else {
11778            // Cluster install
11779            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
11780            info.nativeLibraryRootRequiresIsa = true;
11781
11782            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
11783                    getPrimaryInstructionSet(info)).getAbsolutePath();
11784
11785            if (info.secondaryCpuAbi != null) {
11786                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
11787                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
11788            }
11789        }
11790    }
11791
11792    /**
11793     * Calculate the abis and roots for a bundled app. These can uniquely
11794     * be determined from the contents of the system partition, i.e whether
11795     * it contains 64 or 32 bit shared libraries etc. We do not validate any
11796     * of this information, and instead assume that the system was built
11797     * sensibly.
11798     */
11799    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
11800                                           PackageSetting pkgSetting) {
11801        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
11802
11803        // If "/system/lib64/apkname" exists, assume that is the per-package
11804        // native library directory to use; otherwise use "/system/lib/apkname".
11805        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
11806        setBundledAppAbi(pkg, apkRoot, apkName);
11807        // pkgSetting might be null during rescan following uninstall of updates
11808        // to a bundled app, so accommodate that possibility.  The settings in
11809        // that case will be established later from the parsed package.
11810        //
11811        // If the settings aren't null, sync them up with what we've just derived.
11812        // note that apkRoot isn't stored in the package settings.
11813        if (pkgSetting != null) {
11814            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11815            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11816        }
11817    }
11818
11819    /**
11820     * Deduces the ABI of a bundled app and sets the relevant fields on the
11821     * parsed pkg object.
11822     *
11823     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
11824     *        under which system libraries are installed.
11825     * @param apkName the name of the installed package.
11826     */
11827    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
11828        final File codeFile = new File(pkg.codePath);
11829
11830        final boolean has64BitLibs;
11831        final boolean has32BitLibs;
11832        if (isApkFile(codeFile)) {
11833            // Monolithic install
11834            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
11835            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
11836        } else {
11837            // Cluster install
11838            final File rootDir = new File(codeFile, LIB_DIR_NAME);
11839            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
11840                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
11841                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
11842                has64BitLibs = (new File(rootDir, isa)).exists();
11843            } else {
11844                has64BitLibs = false;
11845            }
11846            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
11847                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
11848                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
11849                has32BitLibs = (new File(rootDir, isa)).exists();
11850            } else {
11851                has32BitLibs = false;
11852            }
11853        }
11854
11855        if (has64BitLibs && !has32BitLibs) {
11856            // The package has 64 bit libs, but not 32 bit libs. Its primary
11857            // ABI should be 64 bit. We can safely assume here that the bundled
11858            // native libraries correspond to the most preferred ABI in the list.
11859
11860            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11861            pkg.applicationInfo.secondaryCpuAbi = null;
11862        } else if (has32BitLibs && !has64BitLibs) {
11863            // The package has 32 bit libs but not 64 bit libs. Its primary
11864            // ABI should be 32 bit.
11865
11866            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11867            pkg.applicationInfo.secondaryCpuAbi = null;
11868        } else if (has32BitLibs && has64BitLibs) {
11869            // The application has both 64 and 32 bit bundled libraries. We check
11870            // here that the app declares multiArch support, and warn if it doesn't.
11871            //
11872            // We will be lenient here and record both ABIs. The primary will be the
11873            // ABI that's higher on the list, i.e, a device that's configured to prefer
11874            // 64 bit apps will see a 64 bit primary ABI,
11875
11876            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
11877                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
11878            }
11879
11880            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
11881                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11882                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11883            } else {
11884                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11885                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11886            }
11887        } else {
11888            pkg.applicationInfo.primaryCpuAbi = null;
11889            pkg.applicationInfo.secondaryCpuAbi = null;
11890        }
11891    }
11892
11893    private void killApplication(String pkgName, int appId, String reason) {
11894        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
11895    }
11896
11897    private void killApplication(String pkgName, int appId, int userId, String reason) {
11898        // Request the ActivityManager to kill the process(only for existing packages)
11899        // so that we do not end up in a confused state while the user is still using the older
11900        // version of the application while the new one gets installed.
11901        final long token = Binder.clearCallingIdentity();
11902        try {
11903            IActivityManager am = ActivityManager.getService();
11904            if (am != null) {
11905                try {
11906                    am.killApplication(pkgName, appId, userId, reason);
11907                } catch (RemoteException e) {
11908                }
11909            }
11910        } finally {
11911            Binder.restoreCallingIdentity(token);
11912        }
11913    }
11914
11915    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
11916        // Remove the parent package setting
11917        PackageSetting ps = (PackageSetting) pkg.mExtras;
11918        if (ps != null) {
11919            removePackageLI(ps, chatty);
11920        }
11921        // Remove the child package setting
11922        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11923        for (int i = 0; i < childCount; i++) {
11924            PackageParser.Package childPkg = pkg.childPackages.get(i);
11925            ps = (PackageSetting) childPkg.mExtras;
11926            if (ps != null) {
11927                removePackageLI(ps, chatty);
11928            }
11929        }
11930    }
11931
11932    void removePackageLI(PackageSetting ps, boolean chatty) {
11933        if (DEBUG_INSTALL) {
11934            if (chatty)
11935                Log.d(TAG, "Removing package " + ps.name);
11936        }
11937
11938        // writer
11939        synchronized (mPackages) {
11940            mPackages.remove(ps.name);
11941            final PackageParser.Package pkg = ps.pkg;
11942            if (pkg != null) {
11943                cleanPackageDataStructuresLILPw(pkg, chatty);
11944            }
11945        }
11946    }
11947
11948    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
11949        if (DEBUG_INSTALL) {
11950            if (chatty)
11951                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
11952        }
11953
11954        // writer
11955        synchronized (mPackages) {
11956            // Remove the parent package
11957            mPackages.remove(pkg.applicationInfo.packageName);
11958            cleanPackageDataStructuresLILPw(pkg, chatty);
11959
11960            // Remove the child packages
11961            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11962            for (int i = 0; i < childCount; i++) {
11963                PackageParser.Package childPkg = pkg.childPackages.get(i);
11964                mPackages.remove(childPkg.applicationInfo.packageName);
11965                cleanPackageDataStructuresLILPw(childPkg, chatty);
11966            }
11967        }
11968    }
11969
11970    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
11971        int N = pkg.providers.size();
11972        StringBuilder r = null;
11973        int i;
11974        for (i=0; i<N; i++) {
11975            PackageParser.Provider p = pkg.providers.get(i);
11976            mProviders.removeProvider(p);
11977            if (p.info.authority == null) {
11978
11979                /* There was another ContentProvider with this authority when
11980                 * this app was installed so this authority is null,
11981                 * Ignore it as we don't have to unregister the provider.
11982                 */
11983                continue;
11984            }
11985            String names[] = p.info.authority.split(";");
11986            for (int j = 0; j < names.length; j++) {
11987                if (mProvidersByAuthority.get(names[j]) == p) {
11988                    mProvidersByAuthority.remove(names[j]);
11989                    if (DEBUG_REMOVE) {
11990                        if (chatty)
11991                            Log.d(TAG, "Unregistered content provider: " + names[j]
11992                                    + ", className = " + p.info.name + ", isSyncable = "
11993                                    + p.info.isSyncable);
11994                    }
11995                }
11996            }
11997            if (DEBUG_REMOVE && chatty) {
11998                if (r == null) {
11999                    r = new StringBuilder(256);
12000                } else {
12001                    r.append(' ');
12002                }
12003                r.append(p.info.name);
12004            }
12005        }
12006        if (r != null) {
12007            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
12008        }
12009
12010        N = pkg.services.size();
12011        r = null;
12012        for (i=0; i<N; i++) {
12013            PackageParser.Service s = pkg.services.get(i);
12014            mServices.removeService(s);
12015            if (chatty) {
12016                if (r == null) {
12017                    r = new StringBuilder(256);
12018                } else {
12019                    r.append(' ');
12020                }
12021                r.append(s.info.name);
12022            }
12023        }
12024        if (r != null) {
12025            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
12026        }
12027
12028        N = pkg.receivers.size();
12029        r = null;
12030        for (i=0; i<N; i++) {
12031            PackageParser.Activity a = pkg.receivers.get(i);
12032            mReceivers.removeActivity(a, "receiver");
12033            if (DEBUG_REMOVE && chatty) {
12034                if (r == null) {
12035                    r = new StringBuilder(256);
12036                } else {
12037                    r.append(' ');
12038                }
12039                r.append(a.info.name);
12040            }
12041        }
12042        if (r != null) {
12043            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
12044        }
12045
12046        N = pkg.activities.size();
12047        r = null;
12048        for (i=0; i<N; i++) {
12049            PackageParser.Activity a = pkg.activities.get(i);
12050            mActivities.removeActivity(a, "activity");
12051            if (DEBUG_REMOVE && chatty) {
12052                if (r == null) {
12053                    r = new StringBuilder(256);
12054                } else {
12055                    r.append(' ');
12056                }
12057                r.append(a.info.name);
12058            }
12059        }
12060        if (r != null) {
12061            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
12062        }
12063
12064        N = pkg.permissions.size();
12065        r = null;
12066        for (i=0; i<N; i++) {
12067            PackageParser.Permission p = pkg.permissions.get(i);
12068            BasePermission bp = mSettings.mPermissions.get(p.info.name);
12069            if (bp == null) {
12070                bp = mSettings.mPermissionTrees.get(p.info.name);
12071            }
12072            if (bp != null && bp.perm == p) {
12073                bp.perm = null;
12074                if (DEBUG_REMOVE && chatty) {
12075                    if (r == null) {
12076                        r = new StringBuilder(256);
12077                    } else {
12078                        r.append(' ');
12079                    }
12080                    r.append(p.info.name);
12081                }
12082            }
12083            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12084                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
12085                if (appOpPkgs != null) {
12086                    appOpPkgs.remove(pkg.packageName);
12087                }
12088            }
12089        }
12090        if (r != null) {
12091            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12092        }
12093
12094        N = pkg.requestedPermissions.size();
12095        r = null;
12096        for (i=0; i<N; i++) {
12097            String perm = pkg.requestedPermissions.get(i);
12098            BasePermission bp = mSettings.mPermissions.get(perm);
12099            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12100                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
12101                if (appOpPkgs != null) {
12102                    appOpPkgs.remove(pkg.packageName);
12103                    if (appOpPkgs.isEmpty()) {
12104                        mAppOpPermissionPackages.remove(perm);
12105                    }
12106                }
12107            }
12108        }
12109        if (r != null) {
12110            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12111        }
12112
12113        N = pkg.instrumentation.size();
12114        r = null;
12115        for (i=0; i<N; i++) {
12116            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
12117            mInstrumentation.remove(a.getComponentName());
12118            if (DEBUG_REMOVE && chatty) {
12119                if (r == null) {
12120                    r = new StringBuilder(256);
12121                } else {
12122                    r.append(' ');
12123                }
12124                r.append(a.info.name);
12125            }
12126        }
12127        if (r != null) {
12128            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
12129        }
12130
12131        r = null;
12132        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
12133            // Only system apps can hold shared libraries.
12134            if (pkg.libraryNames != null) {
12135                for (i = 0; i < pkg.libraryNames.size(); i++) {
12136                    String name = pkg.libraryNames.get(i);
12137                    if (removeSharedLibraryLPw(name, 0)) {
12138                        if (DEBUG_REMOVE && chatty) {
12139                            if (r == null) {
12140                                r = new StringBuilder(256);
12141                            } else {
12142                                r.append(' ');
12143                            }
12144                            r.append(name);
12145                        }
12146                    }
12147                }
12148            }
12149        }
12150
12151        r = null;
12152
12153        // Any package can hold static shared libraries.
12154        if (pkg.staticSharedLibName != null) {
12155            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
12156                if (DEBUG_REMOVE && chatty) {
12157                    if (r == null) {
12158                        r = new StringBuilder(256);
12159                    } else {
12160                        r.append(' ');
12161                    }
12162                    r.append(pkg.staticSharedLibName);
12163                }
12164            }
12165        }
12166
12167        if (r != null) {
12168            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
12169        }
12170    }
12171
12172    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
12173        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
12174            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
12175                return true;
12176            }
12177        }
12178        return false;
12179    }
12180
12181    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
12182    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
12183    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
12184
12185    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
12186        // Update the parent permissions
12187        updatePermissionsLPw(pkg.packageName, pkg, flags);
12188        // Update the child permissions
12189        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12190        for (int i = 0; i < childCount; i++) {
12191            PackageParser.Package childPkg = pkg.childPackages.get(i);
12192            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
12193        }
12194    }
12195
12196    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
12197            int flags) {
12198        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
12199        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
12200    }
12201
12202    private void updatePermissionsLPw(String changingPkg,
12203            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
12204        // Make sure there are no dangling permission trees.
12205        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
12206        while (it.hasNext()) {
12207            final BasePermission bp = it.next();
12208            if (bp.packageSetting == null) {
12209                // We may not yet have parsed the package, so just see if
12210                // we still know about its settings.
12211                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12212            }
12213            if (bp.packageSetting == null) {
12214                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
12215                        + " from package " + bp.sourcePackage);
12216                it.remove();
12217            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12218                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12219                    Slog.i(TAG, "Removing old permission tree: " + bp.name
12220                            + " from package " + bp.sourcePackage);
12221                    flags |= UPDATE_PERMISSIONS_ALL;
12222                    it.remove();
12223                }
12224            }
12225        }
12226
12227        // Make sure all dynamic permissions have been assigned to a package,
12228        // and make sure there are no dangling permissions.
12229        it = mSettings.mPermissions.values().iterator();
12230        while (it.hasNext()) {
12231            final BasePermission bp = it.next();
12232            if (bp.type == BasePermission.TYPE_DYNAMIC) {
12233                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
12234                        + bp.name + " pkg=" + bp.sourcePackage
12235                        + " info=" + bp.pendingInfo);
12236                if (bp.packageSetting == null && bp.pendingInfo != null) {
12237                    final BasePermission tree = findPermissionTreeLP(bp.name);
12238                    if (tree != null && tree.perm != null) {
12239                        bp.packageSetting = tree.packageSetting;
12240                        bp.perm = new PackageParser.Permission(tree.perm.owner,
12241                                new PermissionInfo(bp.pendingInfo));
12242                        bp.perm.info.packageName = tree.perm.info.packageName;
12243                        bp.perm.info.name = bp.name;
12244                        bp.uid = tree.uid;
12245                    }
12246                }
12247            }
12248            if (bp.packageSetting == null) {
12249                // We may not yet have parsed the package, so just see if
12250                // we still know about its settings.
12251                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12252            }
12253            if (bp.packageSetting == null) {
12254                Slog.w(TAG, "Removing dangling permission: " + bp.name
12255                        + " from package " + bp.sourcePackage);
12256                it.remove();
12257            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12258                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12259                    Slog.i(TAG, "Removing old permission: " + bp.name
12260                            + " from package " + bp.sourcePackage);
12261                    flags |= UPDATE_PERMISSIONS_ALL;
12262                    it.remove();
12263                }
12264            }
12265        }
12266
12267        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
12268        // Now update the permissions for all packages, in particular
12269        // replace the granted permissions of the system packages.
12270        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
12271            for (PackageParser.Package pkg : mPackages.values()) {
12272                if (pkg != pkgInfo) {
12273                    // Only replace for packages on requested volume
12274                    final String volumeUuid = getVolumeUuidForPackage(pkg);
12275                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
12276                            && Objects.equals(replaceVolumeUuid, volumeUuid);
12277                    grantPermissionsLPw(pkg, replace, changingPkg);
12278                }
12279            }
12280        }
12281
12282        if (pkgInfo != null) {
12283            // Only replace for packages on requested volume
12284            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
12285            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
12286                    && Objects.equals(replaceVolumeUuid, volumeUuid);
12287            grantPermissionsLPw(pkgInfo, replace, changingPkg);
12288        }
12289        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12290    }
12291
12292    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
12293            String packageOfInterest) {
12294        // IMPORTANT: There are two types of permissions: install and runtime.
12295        // Install time permissions are granted when the app is installed to
12296        // all device users and users added in the future. Runtime permissions
12297        // are granted at runtime explicitly to specific users. Normal and signature
12298        // protected permissions are install time permissions. Dangerous permissions
12299        // are install permissions if the app's target SDK is Lollipop MR1 or older,
12300        // otherwise they are runtime permissions. This function does not manage
12301        // runtime permissions except for the case an app targeting Lollipop MR1
12302        // being upgraded to target a newer SDK, in which case dangerous permissions
12303        // are transformed from install time to runtime ones.
12304
12305        final PackageSetting ps = (PackageSetting) pkg.mExtras;
12306        if (ps == null) {
12307            return;
12308        }
12309
12310        PermissionsState permissionsState = ps.getPermissionsState();
12311        PermissionsState origPermissions = permissionsState;
12312
12313        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
12314
12315        boolean runtimePermissionsRevoked = false;
12316        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
12317
12318        boolean changedInstallPermission = false;
12319
12320        if (replace) {
12321            ps.installPermissionsFixed = false;
12322            if (!ps.isSharedUser()) {
12323                origPermissions = new PermissionsState(permissionsState);
12324                permissionsState.reset();
12325            } else {
12326                // We need to know only about runtime permission changes since the
12327                // calling code always writes the install permissions state but
12328                // the runtime ones are written only if changed. The only cases of
12329                // changed runtime permissions here are promotion of an install to
12330                // runtime and revocation of a runtime from a shared user.
12331                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
12332                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
12333                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
12334                    runtimePermissionsRevoked = true;
12335                }
12336            }
12337        }
12338
12339        permissionsState.setGlobalGids(mGlobalGids);
12340
12341        final int N = pkg.requestedPermissions.size();
12342        for (int i=0; i<N; i++) {
12343            final String name = pkg.requestedPermissions.get(i);
12344            final BasePermission bp = mSettings.mPermissions.get(name);
12345            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
12346                    >= Build.VERSION_CODES.M;
12347
12348            if (DEBUG_INSTALL) {
12349                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
12350            }
12351
12352            if (bp == null || bp.packageSetting == null) {
12353                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
12354                    if (DEBUG_PERMISSIONS) {
12355                        Slog.i(TAG, "Unknown permission " + name
12356                                + " in package " + pkg.packageName);
12357                    }
12358                }
12359                continue;
12360            }
12361
12362
12363            // Limit ephemeral apps to ephemeral allowed permissions.
12364            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
12365                if (DEBUG_PERMISSIONS) {
12366                    Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
12367                            + pkg.packageName);
12368                }
12369                continue;
12370            }
12371
12372            if (bp.isRuntimeOnly() && !appSupportsRuntimePermissions) {
12373                if (DEBUG_PERMISSIONS) {
12374                    Log.i(TAG, "Denying runtime-only permission " + bp.name + " for package "
12375                            + pkg.packageName);
12376                }
12377                continue;
12378            }
12379
12380            final String perm = bp.name;
12381            boolean allowedSig = false;
12382            int grant = GRANT_DENIED;
12383
12384            // Keep track of app op permissions.
12385            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12386                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
12387                if (pkgs == null) {
12388                    pkgs = new ArraySet<>();
12389                    mAppOpPermissionPackages.put(bp.name, pkgs);
12390                }
12391                pkgs.add(pkg.packageName);
12392            }
12393
12394            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
12395            switch (level) {
12396                case PermissionInfo.PROTECTION_NORMAL: {
12397                    // For all apps normal permissions are install time ones.
12398                    grant = GRANT_INSTALL;
12399                } break;
12400
12401                case PermissionInfo.PROTECTION_DANGEROUS: {
12402                    // If a permission review is required for legacy apps we represent
12403                    // their permissions as always granted runtime ones since we need
12404                    // to keep the review required permission flag per user while an
12405                    // install permission's state is shared across all users.
12406                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
12407                        // For legacy apps dangerous permissions are install time ones.
12408                        grant = GRANT_INSTALL;
12409                    } else if (origPermissions.hasInstallPermission(bp.name)) {
12410                        // For legacy apps that became modern, install becomes runtime.
12411                        grant = GRANT_UPGRADE;
12412                    } else if (mPromoteSystemApps
12413                            && isSystemApp(ps)
12414                            && mExistingSystemPackages.contains(ps.name)) {
12415                        // For legacy system apps, install becomes runtime.
12416                        // We cannot check hasInstallPermission() for system apps since those
12417                        // permissions were granted implicitly and not persisted pre-M.
12418                        grant = GRANT_UPGRADE;
12419                    } else {
12420                        // For modern apps keep runtime permissions unchanged.
12421                        grant = GRANT_RUNTIME;
12422                    }
12423                } break;
12424
12425                case PermissionInfo.PROTECTION_SIGNATURE: {
12426                    // For all apps signature permissions are install time ones.
12427                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
12428                    if (allowedSig) {
12429                        grant = GRANT_INSTALL;
12430                    }
12431                } break;
12432            }
12433
12434            if (DEBUG_PERMISSIONS) {
12435                Slog.i(TAG, "Granting permission " + perm + " to package " + pkg.packageName);
12436            }
12437
12438            if (grant != GRANT_DENIED) {
12439                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
12440                    // If this is an existing, non-system package, then
12441                    // we can't add any new permissions to it.
12442                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
12443                        // Except...  if this is a permission that was added
12444                        // to the platform (note: need to only do this when
12445                        // updating the platform).
12446                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
12447                            grant = GRANT_DENIED;
12448                        }
12449                    }
12450                }
12451
12452                switch (grant) {
12453                    case GRANT_INSTALL: {
12454                        // Revoke this as runtime permission to handle the case of
12455                        // a runtime permission being downgraded to an install one.
12456                        // Also in permission review mode we keep dangerous permissions
12457                        // for legacy apps
12458                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12459                            if (origPermissions.getRuntimePermissionState(
12460                                    bp.name, userId) != null) {
12461                                // Revoke the runtime permission and clear the flags.
12462                                origPermissions.revokeRuntimePermission(bp, userId);
12463                                origPermissions.updatePermissionFlags(bp, userId,
12464                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
12465                                // If we revoked a permission permission, we have to write.
12466                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12467                                        changedRuntimePermissionUserIds, userId);
12468                            }
12469                        }
12470                        // Grant an install permission.
12471                        if (permissionsState.grantInstallPermission(bp) !=
12472                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
12473                            changedInstallPermission = true;
12474                        }
12475                    } break;
12476
12477                    case GRANT_RUNTIME: {
12478                        // Grant previously granted runtime permissions.
12479                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12480                            PermissionState permissionState = origPermissions
12481                                    .getRuntimePermissionState(bp.name, userId);
12482                            int flags = permissionState != null
12483                                    ? permissionState.getFlags() : 0;
12484                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
12485                                // Don't propagate the permission in a permission review mode if
12486                                // the former was revoked, i.e. marked to not propagate on upgrade.
12487                                // Note that in a permission review mode install permissions are
12488                                // represented as constantly granted runtime ones since we need to
12489                                // keep a per user state associated with the permission. Also the
12490                                // revoke on upgrade flag is no longer applicable and is reset.
12491                                final boolean revokeOnUpgrade = (flags & PackageManager
12492                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
12493                                if (revokeOnUpgrade) {
12494                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
12495                                    // Since we changed the flags, we have to write.
12496                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12497                                            changedRuntimePermissionUserIds, userId);
12498                                }
12499                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
12500                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
12501                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
12502                                        // If we cannot put the permission as it was,
12503                                        // we have to write.
12504                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12505                                                changedRuntimePermissionUserIds, userId);
12506                                    }
12507                                }
12508
12509                                // If the app supports runtime permissions no need for a review.
12510                                if (mPermissionReviewRequired
12511                                        && appSupportsRuntimePermissions
12512                                        && (flags & PackageManager
12513                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
12514                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
12515                                    // Since we changed the flags, we have to write.
12516                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12517                                            changedRuntimePermissionUserIds, userId);
12518                                }
12519                            } else if (mPermissionReviewRequired
12520                                    && !appSupportsRuntimePermissions) {
12521                                // For legacy apps that need a permission review, every new
12522                                // runtime permission is granted but it is pending a review.
12523                                // We also need to review only platform defined runtime
12524                                // permissions as these are the only ones the platform knows
12525                                // how to disable the API to simulate revocation as legacy
12526                                // apps don't expect to run with revoked permissions.
12527                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
12528                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
12529                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
12530                                        // We changed the flags, hence have to write.
12531                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12532                                                changedRuntimePermissionUserIds, userId);
12533                                    }
12534                                }
12535                                if (permissionsState.grantRuntimePermission(bp, userId)
12536                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
12537                                    // We changed the permission, hence have to write.
12538                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12539                                            changedRuntimePermissionUserIds, userId);
12540                                }
12541                            }
12542                            // Propagate the permission flags.
12543                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
12544                        }
12545                    } break;
12546
12547                    case GRANT_UPGRADE: {
12548                        // Grant runtime permissions for a previously held install permission.
12549                        PermissionState permissionState = origPermissions
12550                                .getInstallPermissionState(bp.name);
12551                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
12552
12553                        if (origPermissions.revokeInstallPermission(bp)
12554                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
12555                            // We will be transferring the permission flags, so clear them.
12556                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
12557                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
12558                            changedInstallPermission = true;
12559                        }
12560
12561                        // If the permission is not to be promoted to runtime we ignore it and
12562                        // also its other flags as they are not applicable to install permissions.
12563                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
12564                            for (int userId : currentUserIds) {
12565                                if (permissionsState.grantRuntimePermission(bp, userId) !=
12566                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
12567                                    // Transfer the permission flags.
12568                                    permissionsState.updatePermissionFlags(bp, userId,
12569                                            flags, flags);
12570                                    // If we granted the permission, we have to write.
12571                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12572                                            changedRuntimePermissionUserIds, userId);
12573                                }
12574                            }
12575                        }
12576                    } break;
12577
12578                    default: {
12579                        if (packageOfInterest == null
12580                                || packageOfInterest.equals(pkg.packageName)) {
12581                            if (DEBUG_PERMISSIONS) {
12582                                Slog.i(TAG, "Not granting permission " + perm
12583                                        + " to package " + pkg.packageName
12584                                        + " because it was previously installed without");
12585                            }
12586                        }
12587                    } break;
12588                }
12589            } else {
12590                if (permissionsState.revokeInstallPermission(bp) !=
12591                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
12592                    // Also drop the permission flags.
12593                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
12594                            PackageManager.MASK_PERMISSION_FLAGS, 0);
12595                    changedInstallPermission = true;
12596                    Slog.i(TAG, "Un-granting permission " + perm
12597                            + " from package " + pkg.packageName
12598                            + " (protectionLevel=" + bp.protectionLevel
12599                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
12600                            + ")");
12601                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
12602                    // Don't print warning for app op permissions, since it is fine for them
12603                    // not to be granted, there is a UI for the user to decide.
12604                    if (DEBUG_PERMISSIONS
12605                            && (packageOfInterest == null
12606                                    || packageOfInterest.equals(pkg.packageName))) {
12607                        Slog.i(TAG, "Not granting permission " + perm
12608                                + " to package " + pkg.packageName
12609                                + " (protectionLevel=" + bp.protectionLevel
12610                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
12611                                + ")");
12612                    }
12613                }
12614            }
12615        }
12616
12617        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
12618                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
12619            // This is the first that we have heard about this package, so the
12620            // permissions we have now selected are fixed until explicitly
12621            // changed.
12622            ps.installPermissionsFixed = true;
12623        }
12624
12625        // Persist the runtime permissions state for users with changes. If permissions
12626        // were revoked because no app in the shared user declares them we have to
12627        // write synchronously to avoid losing runtime permissions state.
12628        for (int userId : changedRuntimePermissionUserIds) {
12629            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
12630        }
12631    }
12632
12633    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
12634        boolean allowed = false;
12635        final int NP = PackageParser.NEW_PERMISSIONS.length;
12636        for (int ip=0; ip<NP; ip++) {
12637            final PackageParser.NewPermissionInfo npi
12638                    = PackageParser.NEW_PERMISSIONS[ip];
12639            if (npi.name.equals(perm)
12640                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
12641                allowed = true;
12642                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
12643                        + pkg.packageName);
12644                break;
12645            }
12646        }
12647        return allowed;
12648    }
12649
12650    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
12651            BasePermission bp, PermissionsState origPermissions) {
12652        boolean privilegedPermission = (bp.protectionLevel
12653                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
12654        boolean privappPermissionsDisable =
12655                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
12656        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
12657        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
12658        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
12659                && !platformPackage && platformPermission) {
12660            ArraySet<String> wlPermissions = SystemConfig.getInstance()
12661                    .getPrivAppPermissions(pkg.packageName);
12662            boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
12663            if (!whitelisted) {
12664                Slog.w(TAG, "Privileged permission " + perm + " for package "
12665                        + pkg.packageName + " - not in privapp-permissions whitelist");
12666                // Only report violations for apps on system image
12667                if (!mSystemReady && !pkg.isUpdatedSystemApp()) {
12668                    if (mPrivappPermissionsViolations == null) {
12669                        mPrivappPermissionsViolations = new ArraySet<>();
12670                    }
12671                    mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
12672                }
12673                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
12674                    return false;
12675                }
12676            }
12677        }
12678        boolean allowed = (compareSignatures(
12679                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
12680                        == PackageManager.SIGNATURE_MATCH)
12681                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
12682                        == PackageManager.SIGNATURE_MATCH);
12683        if (!allowed && privilegedPermission) {
12684            if (isSystemApp(pkg)) {
12685                // For updated system applications, a system permission
12686                // is granted only if it had been defined by the original application.
12687                if (pkg.isUpdatedSystemApp()) {
12688                    final PackageSetting sysPs = mSettings
12689                            .getDisabledSystemPkgLPr(pkg.packageName);
12690                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
12691                        // If the original was granted this permission, we take
12692                        // that grant decision as read and propagate it to the
12693                        // update.
12694                        if (sysPs.isPrivileged()) {
12695                            allowed = true;
12696                        }
12697                    } else {
12698                        // The system apk may have been updated with an older
12699                        // version of the one on the data partition, but which
12700                        // granted a new system permission that it didn't have
12701                        // before.  In this case we do want to allow the app to
12702                        // now get the new permission if the ancestral apk is
12703                        // privileged to get it.
12704                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
12705                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
12706                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
12707                                    allowed = true;
12708                                    break;
12709                                }
12710                            }
12711                        }
12712                        // Also if a privileged parent package on the system image or any of
12713                        // its children requested a privileged permission, the updated child
12714                        // packages can also get the permission.
12715                        if (pkg.parentPackage != null) {
12716                            final PackageSetting disabledSysParentPs = mSettings
12717                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
12718                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
12719                                    && disabledSysParentPs.isPrivileged()) {
12720                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
12721                                    allowed = true;
12722                                } else if (disabledSysParentPs.pkg.childPackages != null) {
12723                                    final int count = disabledSysParentPs.pkg.childPackages.size();
12724                                    for (int i = 0; i < count; i++) {
12725                                        PackageParser.Package disabledSysChildPkg =
12726                                                disabledSysParentPs.pkg.childPackages.get(i);
12727                                        if (isPackageRequestingPermission(disabledSysChildPkg,
12728                                                perm)) {
12729                                            allowed = true;
12730                                            break;
12731                                        }
12732                                    }
12733                                }
12734                            }
12735                        }
12736                    }
12737                } else {
12738                    allowed = isPrivilegedApp(pkg);
12739                }
12740            }
12741        }
12742        if (!allowed) {
12743            if (!allowed && (bp.protectionLevel
12744                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
12745                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
12746                // If this was a previously normal/dangerous permission that got moved
12747                // to a system permission as part of the runtime permission redesign, then
12748                // we still want to blindly grant it to old apps.
12749                allowed = true;
12750            }
12751            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
12752                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
12753                // If this permission is to be granted to the system installer and
12754                // this app is an installer, then it gets the permission.
12755                allowed = true;
12756            }
12757            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
12758                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
12759                // If this permission is to be granted to the system verifier and
12760                // this app is a verifier, then it gets the permission.
12761                allowed = true;
12762            }
12763            if (!allowed && (bp.protectionLevel
12764                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
12765                    && isSystemApp(pkg)) {
12766                // Any pre-installed system app is allowed to get this permission.
12767                allowed = true;
12768            }
12769            if (!allowed && (bp.protectionLevel
12770                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
12771                // For development permissions, a development permission
12772                // is granted only if it was already granted.
12773                allowed = origPermissions.hasInstallPermission(perm);
12774            }
12775            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
12776                    && pkg.packageName.equals(mSetupWizardPackage)) {
12777                // If this permission is to be granted to the system setup wizard and
12778                // this app is a setup wizard, then it gets the permission.
12779                allowed = true;
12780            }
12781        }
12782        return allowed;
12783    }
12784
12785    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
12786        final int permCount = pkg.requestedPermissions.size();
12787        for (int j = 0; j < permCount; j++) {
12788            String requestedPermission = pkg.requestedPermissions.get(j);
12789            if (permission.equals(requestedPermission)) {
12790                return true;
12791            }
12792        }
12793        return false;
12794    }
12795
12796    final class ActivityIntentResolver
12797            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
12798        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12799                boolean defaultOnly, int userId) {
12800            if (!sUserManager.exists(userId)) return null;
12801            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
12802            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12803        }
12804
12805        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12806                int userId) {
12807            if (!sUserManager.exists(userId)) return null;
12808            mFlags = flags;
12809            return super.queryIntent(intent, resolvedType,
12810                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12811                    userId);
12812        }
12813
12814        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12815                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
12816            if (!sUserManager.exists(userId)) return null;
12817            if (packageActivities == null) {
12818                return null;
12819            }
12820            mFlags = flags;
12821            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12822            final int N = packageActivities.size();
12823            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
12824                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
12825
12826            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
12827            for (int i = 0; i < N; ++i) {
12828                intentFilters = packageActivities.get(i).intents;
12829                if (intentFilters != null && intentFilters.size() > 0) {
12830                    PackageParser.ActivityIntentInfo[] array =
12831                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
12832                    intentFilters.toArray(array);
12833                    listCut.add(array);
12834                }
12835            }
12836            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12837        }
12838
12839        /**
12840         * Finds a privileged activity that matches the specified activity names.
12841         */
12842        private PackageParser.Activity findMatchingActivity(
12843                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
12844            for (PackageParser.Activity sysActivity : activityList) {
12845                if (sysActivity.info.name.equals(activityInfo.name)) {
12846                    return sysActivity;
12847                }
12848                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
12849                    return sysActivity;
12850                }
12851                if (sysActivity.info.targetActivity != null) {
12852                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
12853                        return sysActivity;
12854                    }
12855                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
12856                        return sysActivity;
12857                    }
12858                }
12859            }
12860            return null;
12861        }
12862
12863        public class IterGenerator<E> {
12864            public Iterator<E> generate(ActivityIntentInfo info) {
12865                return null;
12866            }
12867        }
12868
12869        public class ActionIterGenerator extends IterGenerator<String> {
12870            @Override
12871            public Iterator<String> generate(ActivityIntentInfo info) {
12872                return info.actionsIterator();
12873            }
12874        }
12875
12876        public class CategoriesIterGenerator extends IterGenerator<String> {
12877            @Override
12878            public Iterator<String> generate(ActivityIntentInfo info) {
12879                return info.categoriesIterator();
12880            }
12881        }
12882
12883        public class SchemesIterGenerator extends IterGenerator<String> {
12884            @Override
12885            public Iterator<String> generate(ActivityIntentInfo info) {
12886                return info.schemesIterator();
12887            }
12888        }
12889
12890        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
12891            @Override
12892            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
12893                return info.authoritiesIterator();
12894            }
12895        }
12896
12897        /**
12898         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
12899         * MODIFIED. Do not pass in a list that should not be changed.
12900         */
12901        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
12902                IterGenerator<T> generator, Iterator<T> searchIterator) {
12903            // loop through the set of actions; every one must be found in the intent filter
12904            while (searchIterator.hasNext()) {
12905                // we must have at least one filter in the list to consider a match
12906                if (intentList.size() == 0) {
12907                    break;
12908                }
12909
12910                final T searchAction = searchIterator.next();
12911
12912                // loop through the set of intent filters
12913                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
12914                while (intentIter.hasNext()) {
12915                    final ActivityIntentInfo intentInfo = intentIter.next();
12916                    boolean selectionFound = false;
12917
12918                    // loop through the intent filter's selection criteria; at least one
12919                    // of them must match the searched criteria
12920                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
12921                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
12922                        final T intentSelection = intentSelectionIter.next();
12923                        if (intentSelection != null && intentSelection.equals(searchAction)) {
12924                            selectionFound = true;
12925                            break;
12926                        }
12927                    }
12928
12929                    // the selection criteria wasn't found in this filter's set; this filter
12930                    // is not a potential match
12931                    if (!selectionFound) {
12932                        intentIter.remove();
12933                    }
12934                }
12935            }
12936        }
12937
12938        private boolean isProtectedAction(ActivityIntentInfo filter) {
12939            final Iterator<String> actionsIter = filter.actionsIterator();
12940            while (actionsIter != null && actionsIter.hasNext()) {
12941                final String filterAction = actionsIter.next();
12942                if (PROTECTED_ACTIONS.contains(filterAction)) {
12943                    return true;
12944                }
12945            }
12946            return false;
12947        }
12948
12949        /**
12950         * Adjusts the priority of the given intent filter according to policy.
12951         * <p>
12952         * <ul>
12953         * <li>The priority for non privileged applications is capped to '0'</li>
12954         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
12955         * <li>The priority for unbundled updates to privileged applications is capped to the
12956         *      priority defined on the system partition</li>
12957         * </ul>
12958         * <p>
12959         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
12960         * allowed to obtain any priority on any action.
12961         */
12962        private void adjustPriority(
12963                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
12964            // nothing to do; priority is fine as-is
12965            if (intent.getPriority() <= 0) {
12966                return;
12967            }
12968
12969            final ActivityInfo activityInfo = intent.activity.info;
12970            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
12971
12972            final boolean privilegedApp =
12973                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
12974            if (!privilegedApp) {
12975                // non-privileged applications can never define a priority >0
12976                if (DEBUG_FILTERS) {
12977                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
12978                            + " package: " + applicationInfo.packageName
12979                            + " activity: " + intent.activity.className
12980                            + " origPrio: " + intent.getPriority());
12981                }
12982                intent.setPriority(0);
12983                return;
12984            }
12985
12986            if (systemActivities == null) {
12987                // the system package is not disabled; we're parsing the system partition
12988                if (isProtectedAction(intent)) {
12989                    if (mDeferProtectedFilters) {
12990                        // We can't deal with these just yet. No component should ever obtain a
12991                        // >0 priority for a protected actions, with ONE exception -- the setup
12992                        // wizard. The setup wizard, however, cannot be known until we're able to
12993                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
12994                        // until all intent filters have been processed. Chicken, meet egg.
12995                        // Let the filter temporarily have a high priority and rectify the
12996                        // priorities after all system packages have been scanned.
12997                        mProtectedFilters.add(intent);
12998                        if (DEBUG_FILTERS) {
12999                            Slog.i(TAG, "Protected action; save for later;"
13000                                    + " package: " + applicationInfo.packageName
13001                                    + " activity: " + intent.activity.className
13002                                    + " origPrio: " + intent.getPriority());
13003                        }
13004                        return;
13005                    } else {
13006                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
13007                            Slog.i(TAG, "No setup wizard;"
13008                                + " All protected intents capped to priority 0");
13009                        }
13010                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
13011                            if (DEBUG_FILTERS) {
13012                                Slog.i(TAG, "Found setup wizard;"
13013                                    + " allow priority " + intent.getPriority() + ";"
13014                                    + " package: " + intent.activity.info.packageName
13015                                    + " activity: " + intent.activity.className
13016                                    + " priority: " + intent.getPriority());
13017                            }
13018                            // setup wizard gets whatever it wants
13019                            return;
13020                        }
13021                        if (DEBUG_FILTERS) {
13022                            Slog.i(TAG, "Protected action; cap priority to 0;"
13023                                    + " package: " + intent.activity.info.packageName
13024                                    + " activity: " + intent.activity.className
13025                                    + " origPrio: " + intent.getPriority());
13026                        }
13027                        intent.setPriority(0);
13028                        return;
13029                    }
13030                }
13031                // privileged apps on the system image get whatever priority they request
13032                return;
13033            }
13034
13035            // privileged app unbundled update ... try to find the same activity
13036            final PackageParser.Activity foundActivity =
13037                    findMatchingActivity(systemActivities, activityInfo);
13038            if (foundActivity == null) {
13039                // this is a new activity; it cannot obtain >0 priority
13040                if (DEBUG_FILTERS) {
13041                    Slog.i(TAG, "New activity; cap priority to 0;"
13042                            + " package: " + applicationInfo.packageName
13043                            + " activity: " + intent.activity.className
13044                            + " origPrio: " + intent.getPriority());
13045                }
13046                intent.setPriority(0);
13047                return;
13048            }
13049
13050            // found activity, now check for filter equivalence
13051
13052            // a shallow copy is enough; we modify the list, not its contents
13053            final List<ActivityIntentInfo> intentListCopy =
13054                    new ArrayList<>(foundActivity.intents);
13055            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
13056
13057            // find matching action subsets
13058            final Iterator<String> actionsIterator = intent.actionsIterator();
13059            if (actionsIterator != null) {
13060                getIntentListSubset(
13061                        intentListCopy, new ActionIterGenerator(), actionsIterator);
13062                if (intentListCopy.size() == 0) {
13063                    // no more intents to match; we're not equivalent
13064                    if (DEBUG_FILTERS) {
13065                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
13066                                + " package: " + applicationInfo.packageName
13067                                + " activity: " + intent.activity.className
13068                                + " origPrio: " + intent.getPriority());
13069                    }
13070                    intent.setPriority(0);
13071                    return;
13072                }
13073            }
13074
13075            // find matching category subsets
13076            final Iterator<String> categoriesIterator = intent.categoriesIterator();
13077            if (categoriesIterator != null) {
13078                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
13079                        categoriesIterator);
13080                if (intentListCopy.size() == 0) {
13081                    // no more intents to match; we're not equivalent
13082                    if (DEBUG_FILTERS) {
13083                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
13084                                + " package: " + applicationInfo.packageName
13085                                + " activity: " + intent.activity.className
13086                                + " origPrio: " + intent.getPriority());
13087                    }
13088                    intent.setPriority(0);
13089                    return;
13090                }
13091            }
13092
13093            // find matching schemes subsets
13094            final Iterator<String> schemesIterator = intent.schemesIterator();
13095            if (schemesIterator != null) {
13096                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
13097                        schemesIterator);
13098                if (intentListCopy.size() == 0) {
13099                    // no more intents to match; we're not equivalent
13100                    if (DEBUG_FILTERS) {
13101                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
13102                                + " package: " + applicationInfo.packageName
13103                                + " activity: " + intent.activity.className
13104                                + " origPrio: " + intent.getPriority());
13105                    }
13106                    intent.setPriority(0);
13107                    return;
13108                }
13109            }
13110
13111            // find matching authorities subsets
13112            final Iterator<IntentFilter.AuthorityEntry>
13113                    authoritiesIterator = intent.authoritiesIterator();
13114            if (authoritiesIterator != null) {
13115                getIntentListSubset(intentListCopy,
13116                        new AuthoritiesIterGenerator(),
13117                        authoritiesIterator);
13118                if (intentListCopy.size() == 0) {
13119                    // no more intents to match; we're not equivalent
13120                    if (DEBUG_FILTERS) {
13121                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
13122                                + " package: " + applicationInfo.packageName
13123                                + " activity: " + intent.activity.className
13124                                + " origPrio: " + intent.getPriority());
13125                    }
13126                    intent.setPriority(0);
13127                    return;
13128                }
13129            }
13130
13131            // we found matching filter(s); app gets the max priority of all intents
13132            int cappedPriority = 0;
13133            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
13134                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
13135            }
13136            if (intent.getPriority() > cappedPriority) {
13137                if (DEBUG_FILTERS) {
13138                    Slog.i(TAG, "Found matching filter(s);"
13139                            + " cap priority to " + cappedPriority + ";"
13140                            + " package: " + applicationInfo.packageName
13141                            + " activity: " + intent.activity.className
13142                            + " origPrio: " + intent.getPriority());
13143                }
13144                intent.setPriority(cappedPriority);
13145                return;
13146            }
13147            // all this for nothing; the requested priority was <= what was on the system
13148        }
13149
13150        public final void addActivity(PackageParser.Activity a, String type) {
13151            mActivities.put(a.getComponentName(), a);
13152            if (DEBUG_SHOW_INFO)
13153                Log.v(
13154                TAG, "  " + type + " " +
13155                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
13156            if (DEBUG_SHOW_INFO)
13157                Log.v(TAG, "    Class=" + a.info.name);
13158            final int NI = a.intents.size();
13159            for (int j=0; j<NI; j++) {
13160                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13161                if ("activity".equals(type)) {
13162                    final PackageSetting ps =
13163                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
13164                    final List<PackageParser.Activity> systemActivities =
13165                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
13166                    adjustPriority(systemActivities, intent);
13167                }
13168                if (DEBUG_SHOW_INFO) {
13169                    Log.v(TAG, "    IntentFilter:");
13170                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13171                }
13172                if (!intent.debugCheck()) {
13173                    Log.w(TAG, "==> For Activity " + a.info.name);
13174                }
13175                addFilter(intent);
13176            }
13177        }
13178
13179        public final void removeActivity(PackageParser.Activity a, String type) {
13180            mActivities.remove(a.getComponentName());
13181            if (DEBUG_SHOW_INFO) {
13182                Log.v(TAG, "  " + type + " "
13183                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
13184                                : a.info.name) + ":");
13185                Log.v(TAG, "    Class=" + a.info.name);
13186            }
13187            final int NI = a.intents.size();
13188            for (int j=0; j<NI; j++) {
13189                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13190                if (DEBUG_SHOW_INFO) {
13191                    Log.v(TAG, "    IntentFilter:");
13192                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13193                }
13194                removeFilter(intent);
13195            }
13196        }
13197
13198        @Override
13199        protected boolean allowFilterResult(
13200                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
13201            ActivityInfo filterAi = filter.activity.info;
13202            for (int i=dest.size()-1; i>=0; i--) {
13203                ActivityInfo destAi = dest.get(i).activityInfo;
13204                if (destAi.name == filterAi.name
13205                        && destAi.packageName == filterAi.packageName) {
13206                    return false;
13207                }
13208            }
13209            return true;
13210        }
13211
13212        @Override
13213        protected ActivityIntentInfo[] newArray(int size) {
13214            return new ActivityIntentInfo[size];
13215        }
13216
13217        @Override
13218        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
13219            if (!sUserManager.exists(userId)) return true;
13220            PackageParser.Package p = filter.activity.owner;
13221            if (p != null) {
13222                PackageSetting ps = (PackageSetting)p.mExtras;
13223                if (ps != null) {
13224                    // System apps are never considered stopped for purposes of
13225                    // filtering, because there may be no way for the user to
13226                    // actually re-launch them.
13227                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
13228                            && ps.getStopped(userId);
13229                }
13230            }
13231            return false;
13232        }
13233
13234        @Override
13235        protected boolean isPackageForFilter(String packageName,
13236                PackageParser.ActivityIntentInfo info) {
13237            return packageName.equals(info.activity.owner.packageName);
13238        }
13239
13240        @Override
13241        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
13242                int match, int userId) {
13243            if (!sUserManager.exists(userId)) return null;
13244            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
13245                return null;
13246            }
13247            final PackageParser.Activity activity = info.activity;
13248            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
13249            if (ps == null) {
13250                return null;
13251            }
13252            final PackageUserState userState = ps.readUserState(userId);
13253            ActivityInfo ai =
13254                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
13255            if (ai == null) {
13256                return null;
13257            }
13258            final boolean matchExplicitlyVisibleOnly =
13259                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
13260            final boolean matchVisibleToInstantApp =
13261                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13262            final boolean componentVisible =
13263                    matchVisibleToInstantApp
13264                    && info.isVisibleToInstantApp()
13265                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
13266            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13267            // throw out filters that aren't visible to ephemeral apps
13268            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
13269                return null;
13270            }
13271            // throw out instant app filters if we're not explicitly requesting them
13272            if (!matchInstantApp && userState.instantApp) {
13273                return null;
13274            }
13275            // throw out instant app filters if updates are available; will trigger
13276            // instant app resolution
13277            if (userState.instantApp && ps.isUpdateAvailable()) {
13278                return null;
13279            }
13280            final ResolveInfo res = new ResolveInfo();
13281            res.activityInfo = ai;
13282            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13283                res.filter = info;
13284            }
13285            if (info != null) {
13286                res.handleAllWebDataURI = info.handleAllWebDataURI();
13287            }
13288            res.priority = info.getPriority();
13289            res.preferredOrder = activity.owner.mPreferredOrder;
13290            //System.out.println("Result: " + res.activityInfo.className +
13291            //                   " = " + res.priority);
13292            res.match = match;
13293            res.isDefault = info.hasDefault;
13294            res.labelRes = info.labelRes;
13295            res.nonLocalizedLabel = info.nonLocalizedLabel;
13296            if (userNeedsBadging(userId)) {
13297                res.noResourceId = true;
13298            } else {
13299                res.icon = info.icon;
13300            }
13301            res.iconResourceId = info.icon;
13302            res.system = res.activityInfo.applicationInfo.isSystemApp();
13303            res.isInstantAppAvailable = userState.instantApp;
13304            return res;
13305        }
13306
13307        @Override
13308        protected void sortResults(List<ResolveInfo> results) {
13309            Collections.sort(results, mResolvePrioritySorter);
13310        }
13311
13312        @Override
13313        protected void dumpFilter(PrintWriter out, String prefix,
13314                PackageParser.ActivityIntentInfo filter) {
13315            out.print(prefix); out.print(
13316                    Integer.toHexString(System.identityHashCode(filter.activity)));
13317                    out.print(' ');
13318                    filter.activity.printComponentShortName(out);
13319                    out.print(" filter ");
13320                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13321        }
13322
13323        @Override
13324        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
13325            return filter.activity;
13326        }
13327
13328        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13329            PackageParser.Activity activity = (PackageParser.Activity)label;
13330            out.print(prefix); out.print(
13331                    Integer.toHexString(System.identityHashCode(activity)));
13332                    out.print(' ');
13333                    activity.printComponentShortName(out);
13334            if (count > 1) {
13335                out.print(" ("); out.print(count); out.print(" filters)");
13336            }
13337            out.println();
13338        }
13339
13340        // Keys are String (activity class name), values are Activity.
13341        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
13342                = new ArrayMap<ComponentName, PackageParser.Activity>();
13343        private int mFlags;
13344    }
13345
13346    private final class ServiceIntentResolver
13347            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
13348        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13349                boolean defaultOnly, int userId) {
13350            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13351            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13352        }
13353
13354        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13355                int userId) {
13356            if (!sUserManager.exists(userId)) return null;
13357            mFlags = flags;
13358            return super.queryIntent(intent, resolvedType,
13359                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13360                    userId);
13361        }
13362
13363        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13364                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
13365            if (!sUserManager.exists(userId)) return null;
13366            if (packageServices == null) {
13367                return null;
13368            }
13369            mFlags = flags;
13370            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
13371            final int N = packageServices.size();
13372            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
13373                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
13374
13375            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
13376            for (int i = 0; i < N; ++i) {
13377                intentFilters = packageServices.get(i).intents;
13378                if (intentFilters != null && intentFilters.size() > 0) {
13379                    PackageParser.ServiceIntentInfo[] array =
13380                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
13381                    intentFilters.toArray(array);
13382                    listCut.add(array);
13383                }
13384            }
13385            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13386        }
13387
13388        public final void addService(PackageParser.Service s) {
13389            mServices.put(s.getComponentName(), s);
13390            if (DEBUG_SHOW_INFO) {
13391                Log.v(TAG, "  "
13392                        + (s.info.nonLocalizedLabel != null
13393                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13394                Log.v(TAG, "    Class=" + s.info.name);
13395            }
13396            final int NI = s.intents.size();
13397            int j;
13398            for (j=0; j<NI; j++) {
13399                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13400                if (DEBUG_SHOW_INFO) {
13401                    Log.v(TAG, "    IntentFilter:");
13402                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13403                }
13404                if (!intent.debugCheck()) {
13405                    Log.w(TAG, "==> For Service " + s.info.name);
13406                }
13407                addFilter(intent);
13408            }
13409        }
13410
13411        public final void removeService(PackageParser.Service s) {
13412            mServices.remove(s.getComponentName());
13413            if (DEBUG_SHOW_INFO) {
13414                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
13415                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13416                Log.v(TAG, "    Class=" + s.info.name);
13417            }
13418            final int NI = s.intents.size();
13419            int j;
13420            for (j=0; j<NI; j++) {
13421                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13422                if (DEBUG_SHOW_INFO) {
13423                    Log.v(TAG, "    IntentFilter:");
13424                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13425                }
13426                removeFilter(intent);
13427            }
13428        }
13429
13430        @Override
13431        protected boolean allowFilterResult(
13432                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
13433            ServiceInfo filterSi = filter.service.info;
13434            for (int i=dest.size()-1; i>=0; i--) {
13435                ServiceInfo destAi = dest.get(i).serviceInfo;
13436                if (destAi.name == filterSi.name
13437                        && destAi.packageName == filterSi.packageName) {
13438                    return false;
13439                }
13440            }
13441            return true;
13442        }
13443
13444        @Override
13445        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
13446            return new PackageParser.ServiceIntentInfo[size];
13447        }
13448
13449        @Override
13450        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
13451            if (!sUserManager.exists(userId)) return true;
13452            PackageParser.Package p = filter.service.owner;
13453            if (p != null) {
13454                PackageSetting ps = (PackageSetting)p.mExtras;
13455                if (ps != null) {
13456                    // System apps are never considered stopped for purposes of
13457                    // filtering, because there may be no way for the user to
13458                    // actually re-launch them.
13459                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13460                            && ps.getStopped(userId);
13461                }
13462            }
13463            return false;
13464        }
13465
13466        @Override
13467        protected boolean isPackageForFilter(String packageName,
13468                PackageParser.ServiceIntentInfo info) {
13469            return packageName.equals(info.service.owner.packageName);
13470        }
13471
13472        @Override
13473        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
13474                int match, int userId) {
13475            if (!sUserManager.exists(userId)) return null;
13476            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
13477            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
13478                return null;
13479            }
13480            final PackageParser.Service service = info.service;
13481            PackageSetting ps = (PackageSetting) service.owner.mExtras;
13482            if (ps == null) {
13483                return null;
13484            }
13485            final PackageUserState userState = ps.readUserState(userId);
13486            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
13487                    userState, userId);
13488            if (si == null) {
13489                return null;
13490            }
13491            final boolean matchVisibleToInstantApp =
13492                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13493            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13494            // throw out filters that aren't visible to ephemeral apps
13495            if (matchVisibleToInstantApp
13496                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13497                return null;
13498            }
13499            // throw out ephemeral filters if we're not explicitly requesting them
13500            if (!isInstantApp && userState.instantApp) {
13501                return null;
13502            }
13503            // throw out instant app filters if updates are available; will trigger
13504            // instant app resolution
13505            if (userState.instantApp && ps.isUpdateAvailable()) {
13506                return null;
13507            }
13508            final ResolveInfo res = new ResolveInfo();
13509            res.serviceInfo = si;
13510            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13511                res.filter = filter;
13512            }
13513            res.priority = info.getPriority();
13514            res.preferredOrder = service.owner.mPreferredOrder;
13515            res.match = match;
13516            res.isDefault = info.hasDefault;
13517            res.labelRes = info.labelRes;
13518            res.nonLocalizedLabel = info.nonLocalizedLabel;
13519            res.icon = info.icon;
13520            res.system = res.serviceInfo.applicationInfo.isSystemApp();
13521            return res;
13522        }
13523
13524        @Override
13525        protected void sortResults(List<ResolveInfo> results) {
13526            Collections.sort(results, mResolvePrioritySorter);
13527        }
13528
13529        @Override
13530        protected void dumpFilter(PrintWriter out, String prefix,
13531                PackageParser.ServiceIntentInfo filter) {
13532            out.print(prefix); out.print(
13533                    Integer.toHexString(System.identityHashCode(filter.service)));
13534                    out.print(' ');
13535                    filter.service.printComponentShortName(out);
13536                    out.print(" filter ");
13537                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13538        }
13539
13540        @Override
13541        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
13542            return filter.service;
13543        }
13544
13545        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13546            PackageParser.Service service = (PackageParser.Service)label;
13547            out.print(prefix); out.print(
13548                    Integer.toHexString(System.identityHashCode(service)));
13549                    out.print(' ');
13550                    service.printComponentShortName(out);
13551            if (count > 1) {
13552                out.print(" ("); out.print(count); out.print(" filters)");
13553            }
13554            out.println();
13555        }
13556
13557//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
13558//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
13559//            final List<ResolveInfo> retList = Lists.newArrayList();
13560//            while (i.hasNext()) {
13561//                final ResolveInfo resolveInfo = (ResolveInfo) i;
13562//                if (isEnabledLP(resolveInfo.serviceInfo)) {
13563//                    retList.add(resolveInfo);
13564//                }
13565//            }
13566//            return retList;
13567//        }
13568
13569        // Keys are String (activity class name), values are Activity.
13570        private final ArrayMap<ComponentName, PackageParser.Service> mServices
13571                = new ArrayMap<ComponentName, PackageParser.Service>();
13572        private int mFlags;
13573    }
13574
13575    private final class ProviderIntentResolver
13576            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
13577        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13578                boolean defaultOnly, int userId) {
13579            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13580            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13581        }
13582
13583        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13584                int userId) {
13585            if (!sUserManager.exists(userId))
13586                return null;
13587            mFlags = flags;
13588            return super.queryIntent(intent, resolvedType,
13589                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13590                    userId);
13591        }
13592
13593        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13594                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
13595            if (!sUserManager.exists(userId))
13596                return null;
13597            if (packageProviders == null) {
13598                return null;
13599            }
13600            mFlags = flags;
13601            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
13602            final int N = packageProviders.size();
13603            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
13604                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
13605
13606            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
13607            for (int i = 0; i < N; ++i) {
13608                intentFilters = packageProviders.get(i).intents;
13609                if (intentFilters != null && intentFilters.size() > 0) {
13610                    PackageParser.ProviderIntentInfo[] array =
13611                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
13612                    intentFilters.toArray(array);
13613                    listCut.add(array);
13614                }
13615            }
13616            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13617        }
13618
13619        public final void addProvider(PackageParser.Provider p) {
13620            if (mProviders.containsKey(p.getComponentName())) {
13621                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
13622                return;
13623            }
13624
13625            mProviders.put(p.getComponentName(), p);
13626            if (DEBUG_SHOW_INFO) {
13627                Log.v(TAG, "  "
13628                        + (p.info.nonLocalizedLabel != null
13629                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
13630                Log.v(TAG, "    Class=" + p.info.name);
13631            }
13632            final int NI = p.intents.size();
13633            int j;
13634            for (j = 0; j < NI; j++) {
13635                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13636                if (DEBUG_SHOW_INFO) {
13637                    Log.v(TAG, "    IntentFilter:");
13638                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13639                }
13640                if (!intent.debugCheck()) {
13641                    Log.w(TAG, "==> For Provider " + p.info.name);
13642                }
13643                addFilter(intent);
13644            }
13645        }
13646
13647        public final void removeProvider(PackageParser.Provider p) {
13648            mProviders.remove(p.getComponentName());
13649            if (DEBUG_SHOW_INFO) {
13650                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
13651                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
13652                Log.v(TAG, "    Class=" + p.info.name);
13653            }
13654            final int NI = p.intents.size();
13655            int j;
13656            for (j = 0; j < NI; j++) {
13657                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13658                if (DEBUG_SHOW_INFO) {
13659                    Log.v(TAG, "    IntentFilter:");
13660                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13661                }
13662                removeFilter(intent);
13663            }
13664        }
13665
13666        @Override
13667        protected boolean allowFilterResult(
13668                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
13669            ProviderInfo filterPi = filter.provider.info;
13670            for (int i = dest.size() - 1; i >= 0; i--) {
13671                ProviderInfo destPi = dest.get(i).providerInfo;
13672                if (destPi.name == filterPi.name
13673                        && destPi.packageName == filterPi.packageName) {
13674                    return false;
13675                }
13676            }
13677            return true;
13678        }
13679
13680        @Override
13681        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
13682            return new PackageParser.ProviderIntentInfo[size];
13683        }
13684
13685        @Override
13686        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
13687            if (!sUserManager.exists(userId))
13688                return true;
13689            PackageParser.Package p = filter.provider.owner;
13690            if (p != null) {
13691                PackageSetting ps = (PackageSetting) p.mExtras;
13692                if (ps != null) {
13693                    // System apps are never considered stopped for purposes of
13694                    // filtering, because there may be no way for the user to
13695                    // actually re-launch them.
13696                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13697                            && ps.getStopped(userId);
13698                }
13699            }
13700            return false;
13701        }
13702
13703        @Override
13704        protected boolean isPackageForFilter(String packageName,
13705                PackageParser.ProviderIntentInfo info) {
13706            return packageName.equals(info.provider.owner.packageName);
13707        }
13708
13709        @Override
13710        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
13711                int match, int userId) {
13712            if (!sUserManager.exists(userId))
13713                return null;
13714            final PackageParser.ProviderIntentInfo info = filter;
13715            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
13716                return null;
13717            }
13718            final PackageParser.Provider provider = info.provider;
13719            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
13720            if (ps == null) {
13721                return null;
13722            }
13723            final PackageUserState userState = ps.readUserState(userId);
13724            final boolean matchVisibleToInstantApp =
13725                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13726            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13727            // throw out filters that aren't visible to instant applications
13728            if (matchVisibleToInstantApp
13729                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13730                return null;
13731            }
13732            // throw out instant application filters if we're not explicitly requesting them
13733            if (!isInstantApp && userState.instantApp) {
13734                return null;
13735            }
13736            // throw out instant application filters if updates are available; will trigger
13737            // instant application resolution
13738            if (userState.instantApp && ps.isUpdateAvailable()) {
13739                return null;
13740            }
13741            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
13742                    userState, userId);
13743            if (pi == null) {
13744                return null;
13745            }
13746            final ResolveInfo res = new ResolveInfo();
13747            res.providerInfo = pi;
13748            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
13749                res.filter = filter;
13750            }
13751            res.priority = info.getPriority();
13752            res.preferredOrder = provider.owner.mPreferredOrder;
13753            res.match = match;
13754            res.isDefault = info.hasDefault;
13755            res.labelRes = info.labelRes;
13756            res.nonLocalizedLabel = info.nonLocalizedLabel;
13757            res.icon = info.icon;
13758            res.system = res.providerInfo.applicationInfo.isSystemApp();
13759            return res;
13760        }
13761
13762        @Override
13763        protected void sortResults(List<ResolveInfo> results) {
13764            Collections.sort(results, mResolvePrioritySorter);
13765        }
13766
13767        @Override
13768        protected void dumpFilter(PrintWriter out, String prefix,
13769                PackageParser.ProviderIntentInfo filter) {
13770            out.print(prefix);
13771            out.print(
13772                    Integer.toHexString(System.identityHashCode(filter.provider)));
13773            out.print(' ');
13774            filter.provider.printComponentShortName(out);
13775            out.print(" filter ");
13776            out.println(Integer.toHexString(System.identityHashCode(filter)));
13777        }
13778
13779        @Override
13780        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
13781            return filter.provider;
13782        }
13783
13784        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13785            PackageParser.Provider provider = (PackageParser.Provider)label;
13786            out.print(prefix); out.print(
13787                    Integer.toHexString(System.identityHashCode(provider)));
13788                    out.print(' ');
13789                    provider.printComponentShortName(out);
13790            if (count > 1) {
13791                out.print(" ("); out.print(count); out.print(" filters)");
13792            }
13793            out.println();
13794        }
13795
13796        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
13797                = new ArrayMap<ComponentName, PackageParser.Provider>();
13798        private int mFlags;
13799    }
13800
13801    static final class EphemeralIntentResolver
13802            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
13803        /**
13804         * The result that has the highest defined order. Ordering applies on a
13805         * per-package basis. Mapping is from package name to Pair of order and
13806         * EphemeralResolveInfo.
13807         * <p>
13808         * NOTE: This is implemented as a field variable for convenience and efficiency.
13809         * By having a field variable, we're able to track filter ordering as soon as
13810         * a non-zero order is defined. Otherwise, multiple loops across the result set
13811         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
13812         * this needs to be contained entirely within {@link #filterResults}.
13813         */
13814        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
13815
13816        @Override
13817        protected AuxiliaryResolveInfo[] newArray(int size) {
13818            return new AuxiliaryResolveInfo[size];
13819        }
13820
13821        @Override
13822        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
13823            return true;
13824        }
13825
13826        @Override
13827        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
13828                int userId) {
13829            if (!sUserManager.exists(userId)) {
13830                return null;
13831            }
13832            final String packageName = responseObj.resolveInfo.getPackageName();
13833            final Integer order = responseObj.getOrder();
13834            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
13835                    mOrderResult.get(packageName);
13836            // ordering is enabled and this item's order isn't high enough
13837            if (lastOrderResult != null && lastOrderResult.first >= order) {
13838                return null;
13839            }
13840            final InstantAppResolveInfo res = responseObj.resolveInfo;
13841            if (order > 0) {
13842                // non-zero order, enable ordering
13843                mOrderResult.put(packageName, new Pair<>(order, res));
13844            }
13845            return responseObj;
13846        }
13847
13848        @Override
13849        protected void filterResults(List<AuxiliaryResolveInfo> results) {
13850            // only do work if ordering is enabled [most of the time it won't be]
13851            if (mOrderResult.size() == 0) {
13852                return;
13853            }
13854            int resultSize = results.size();
13855            for (int i = 0; i < resultSize; i++) {
13856                final InstantAppResolveInfo info = results.get(i).resolveInfo;
13857                final String packageName = info.getPackageName();
13858                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
13859                if (savedInfo == null) {
13860                    // package doesn't having ordering
13861                    continue;
13862                }
13863                if (savedInfo.second == info) {
13864                    // circled back to the highest ordered item; remove from order list
13865                    mOrderResult.remove(savedInfo);
13866                    if (mOrderResult.size() == 0) {
13867                        // no more ordered items
13868                        break;
13869                    }
13870                    continue;
13871                }
13872                // item has a worse order, remove it from the result list
13873                results.remove(i);
13874                resultSize--;
13875                i--;
13876            }
13877        }
13878    }
13879
13880    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
13881            new Comparator<ResolveInfo>() {
13882        public int compare(ResolveInfo r1, ResolveInfo r2) {
13883            int v1 = r1.priority;
13884            int v2 = r2.priority;
13885            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
13886            if (v1 != v2) {
13887                return (v1 > v2) ? -1 : 1;
13888            }
13889            v1 = r1.preferredOrder;
13890            v2 = r2.preferredOrder;
13891            if (v1 != v2) {
13892                return (v1 > v2) ? -1 : 1;
13893            }
13894            if (r1.isDefault != r2.isDefault) {
13895                return r1.isDefault ? -1 : 1;
13896            }
13897            v1 = r1.match;
13898            v2 = r2.match;
13899            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
13900            if (v1 != v2) {
13901                return (v1 > v2) ? -1 : 1;
13902            }
13903            if (r1.system != r2.system) {
13904                return r1.system ? -1 : 1;
13905            }
13906            if (r1.activityInfo != null) {
13907                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
13908            }
13909            if (r1.serviceInfo != null) {
13910                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
13911            }
13912            if (r1.providerInfo != null) {
13913                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
13914            }
13915            return 0;
13916        }
13917    };
13918
13919    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
13920            new Comparator<ProviderInfo>() {
13921        public int compare(ProviderInfo p1, ProviderInfo p2) {
13922            final int v1 = p1.initOrder;
13923            final int v2 = p2.initOrder;
13924            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
13925        }
13926    };
13927
13928    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
13929            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
13930            final int[] userIds) {
13931        mHandler.post(new Runnable() {
13932            @Override
13933            public void run() {
13934                try {
13935                    final IActivityManager am = ActivityManager.getService();
13936                    if (am == null) return;
13937                    final int[] resolvedUserIds;
13938                    if (userIds == null) {
13939                        resolvedUserIds = am.getRunningUserIds();
13940                    } else {
13941                        resolvedUserIds = userIds;
13942                    }
13943                    for (int id : resolvedUserIds) {
13944                        final Intent intent = new Intent(action,
13945                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
13946                        if (extras != null) {
13947                            intent.putExtras(extras);
13948                        }
13949                        if (targetPkg != null) {
13950                            intent.setPackage(targetPkg);
13951                        }
13952                        // Modify the UID when posting to other users
13953                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
13954                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
13955                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
13956                            intent.putExtra(Intent.EXTRA_UID, uid);
13957                        }
13958                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
13959                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
13960                        if (DEBUG_BROADCASTS) {
13961                            RuntimeException here = new RuntimeException("here");
13962                            here.fillInStackTrace();
13963                            Slog.d(TAG, "Sending to user " + id + ": "
13964                                    + intent.toShortString(false, true, false, false)
13965                                    + " " + intent.getExtras(), here);
13966                        }
13967                        am.broadcastIntent(null, intent, null, finishedReceiver,
13968                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
13969                                null, finishedReceiver != null, false, id);
13970                    }
13971                } catch (RemoteException ex) {
13972                }
13973            }
13974        });
13975    }
13976
13977    /**
13978     * Check if the external storage media is available. This is true if there
13979     * is a mounted external storage medium or if the external storage is
13980     * emulated.
13981     */
13982    private boolean isExternalMediaAvailable() {
13983        return mMediaMounted || Environment.isExternalStorageEmulated();
13984    }
13985
13986    @Override
13987    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
13988        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
13989            return null;
13990        }
13991        // writer
13992        synchronized (mPackages) {
13993            if (!isExternalMediaAvailable()) {
13994                // If the external storage is no longer mounted at this point,
13995                // the caller may not have been able to delete all of this
13996                // packages files and can not delete any more.  Bail.
13997                return null;
13998            }
13999            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
14000            if (lastPackage != null) {
14001                pkgs.remove(lastPackage);
14002            }
14003            if (pkgs.size() > 0) {
14004                return pkgs.get(0);
14005            }
14006        }
14007        return null;
14008    }
14009
14010    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
14011        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
14012                userId, andCode ? 1 : 0, packageName);
14013        if (mSystemReady) {
14014            msg.sendToTarget();
14015        } else {
14016            if (mPostSystemReadyMessages == null) {
14017                mPostSystemReadyMessages = new ArrayList<>();
14018            }
14019            mPostSystemReadyMessages.add(msg);
14020        }
14021    }
14022
14023    void startCleaningPackages() {
14024        // reader
14025        if (!isExternalMediaAvailable()) {
14026            return;
14027        }
14028        synchronized (mPackages) {
14029            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
14030                return;
14031            }
14032        }
14033        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
14034        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
14035        IActivityManager am = ActivityManager.getService();
14036        if (am != null) {
14037            int dcsUid = -1;
14038            synchronized (mPackages) {
14039                if (!mDefaultContainerWhitelisted) {
14040                    mDefaultContainerWhitelisted = true;
14041                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
14042                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
14043                }
14044            }
14045            try {
14046                if (dcsUid > 0) {
14047                    am.backgroundWhitelistUid(dcsUid);
14048                }
14049                am.startService(null, intent, null, false, mContext.getOpPackageName(),
14050                        UserHandle.USER_SYSTEM);
14051            } catch (RemoteException e) {
14052            }
14053        }
14054    }
14055
14056    @Override
14057    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
14058            int installFlags, String installerPackageName, int userId) {
14059        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
14060
14061        final int callingUid = Binder.getCallingUid();
14062        enforceCrossUserPermission(callingUid, userId,
14063                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
14064
14065        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14066            try {
14067                if (observer != null) {
14068                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
14069                }
14070            } catch (RemoteException re) {
14071            }
14072            return;
14073        }
14074
14075        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
14076            installFlags |= PackageManager.INSTALL_FROM_ADB;
14077
14078        } else {
14079            // Caller holds INSTALL_PACKAGES permission, so we're less strict
14080            // about installerPackageName.
14081
14082            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
14083            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
14084        }
14085
14086        UserHandle user;
14087        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
14088            user = UserHandle.ALL;
14089        } else {
14090            user = new UserHandle(userId);
14091        }
14092
14093        // Only system components can circumvent runtime permissions when installing.
14094        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
14095                && mContext.checkCallingOrSelfPermission(Manifest.permission
14096                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
14097            throw new SecurityException("You need the "
14098                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
14099                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
14100        }
14101
14102        if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
14103                || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
14104            throw new IllegalArgumentException(
14105                    "New installs into ASEC containers no longer supported");
14106        }
14107
14108        final File originFile = new File(originPath);
14109        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
14110
14111        final Message msg = mHandler.obtainMessage(INIT_COPY);
14112        final VerificationInfo verificationInfo = new VerificationInfo(
14113                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
14114        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
14115                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
14116                null /*packageAbiOverride*/, null /*grantedPermissions*/,
14117                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
14118        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
14119        msg.obj = params;
14120
14121        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
14122                System.identityHashCode(msg.obj));
14123        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14124                System.identityHashCode(msg.obj));
14125
14126        mHandler.sendMessage(msg);
14127    }
14128
14129
14130    /**
14131     * Ensure that the install reason matches what we know about the package installer (e.g. whether
14132     * it is acting on behalf on an enterprise or the user).
14133     *
14134     * Note that the ordering of the conditionals in this method is important. The checks we perform
14135     * are as follows, in this order:
14136     *
14137     * 1) If the install is being performed by a system app, we can trust the app to have set the
14138     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
14139     *    what it is.
14140     * 2) If the install is being performed by a device or profile owner app, the install reason
14141     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
14142     *    set the install reason correctly. If the app targets an older SDK version where install
14143     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
14144     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
14145     * 3) In all other cases, the install is being performed by a regular app that is neither part
14146     *    of the system nor a device or profile owner. We have no reason to believe that this app is
14147     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
14148     *    set to enterprise policy and if so, change it to unknown instead.
14149     */
14150    private int fixUpInstallReason(String installerPackageName, int installerUid,
14151            int installReason) {
14152        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
14153                == PERMISSION_GRANTED) {
14154            // If the install is being performed by a system app, we trust that app to have set the
14155            // install reason correctly.
14156            return installReason;
14157        }
14158
14159        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
14160            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
14161        if (dpm != null) {
14162            ComponentName owner = null;
14163            try {
14164                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
14165                if (owner == null) {
14166                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
14167                }
14168            } catch (RemoteException e) {
14169            }
14170            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
14171                // If the install is being performed by a device or profile owner, the install
14172                // reason should be enterprise policy.
14173                return PackageManager.INSTALL_REASON_POLICY;
14174            }
14175        }
14176
14177        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
14178            // If the install is being performed by a regular app (i.e. neither system app nor
14179            // device or profile owner), we have no reason to believe that the app is acting on
14180            // behalf of an enterprise. If the app set the install reason to enterprise policy,
14181            // change it to unknown instead.
14182            return PackageManager.INSTALL_REASON_UNKNOWN;
14183        }
14184
14185        // If the install is being performed by a regular app and the install reason was set to any
14186        // value but enterprise policy, leave the install reason unchanged.
14187        return installReason;
14188    }
14189
14190    void installStage(String packageName, File stagedDir, String stagedCid,
14191            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
14192            String installerPackageName, int installerUid, UserHandle user,
14193            Certificate[][] certificates) {
14194        if (DEBUG_EPHEMERAL) {
14195            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14196                Slog.d(TAG, "Ephemeral install of " + packageName);
14197            }
14198        }
14199        final VerificationInfo verificationInfo = new VerificationInfo(
14200                sessionParams.originatingUri, sessionParams.referrerUri,
14201                sessionParams.originatingUid, installerUid);
14202
14203        final OriginInfo origin;
14204        if (stagedDir != null) {
14205            origin = OriginInfo.fromStagedFile(stagedDir);
14206        } else {
14207            origin = OriginInfo.fromStagedContainer(stagedCid);
14208        }
14209
14210        final Message msg = mHandler.obtainMessage(INIT_COPY);
14211        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
14212                sessionParams.installReason);
14213        final InstallParams params = new InstallParams(origin, null, observer,
14214                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
14215                verificationInfo, user, sessionParams.abiOverride,
14216                sessionParams.grantedRuntimePermissions, certificates, installReason);
14217        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
14218        msg.obj = params;
14219
14220        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
14221                System.identityHashCode(msg.obj));
14222        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14223                System.identityHashCode(msg.obj));
14224
14225        mHandler.sendMessage(msg);
14226    }
14227
14228    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
14229            int userId) {
14230        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
14231        sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId);
14232
14233        // Send a session commit broadcast
14234        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
14235        info.installReason = pkgSetting.getInstallReason(userId);
14236        info.appPackageName = packageName;
14237        sendSessionCommitBroadcast(info, userId);
14238    }
14239
14240    public void sendPackageAddedForNewUsers(String packageName, boolean isSystem, int appId, int... userIds) {
14241        if (ArrayUtils.isEmpty(userIds)) {
14242            return;
14243        }
14244        Bundle extras = new Bundle(1);
14245        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
14246        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
14247
14248        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
14249                packageName, extras, 0, null, null, userIds);
14250        if (isSystem) {
14251            mHandler.post(() -> {
14252                        for (int userId : userIds) {
14253                            sendBootCompletedBroadcastToSystemApp(packageName, userId);
14254                        }
14255                    }
14256            );
14257        }
14258    }
14259
14260    /**
14261     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
14262     * automatically without needing an explicit launch.
14263     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
14264     */
14265    private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) {
14266        // If user is not running, the app didn't miss any broadcast
14267        if (!mUserManagerInternal.isUserRunning(userId)) {
14268            return;
14269        }
14270        final IActivityManager am = ActivityManager.getService();
14271        try {
14272            // Deliver LOCKED_BOOT_COMPLETED first
14273            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
14274                    .setPackage(packageName);
14275            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
14276            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
14277                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14278
14279            // Deliver BOOT_COMPLETED only if user is unlocked
14280            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
14281                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
14282                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
14283                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14284            }
14285        } catch (RemoteException e) {
14286            throw e.rethrowFromSystemServer();
14287        }
14288    }
14289
14290    @Override
14291    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
14292            int userId) {
14293        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14294        PackageSetting pkgSetting;
14295        final int callingUid = Binder.getCallingUid();
14296        enforceCrossUserPermission(callingUid, userId,
14297                true /* requireFullPermission */, true /* checkShell */,
14298                "setApplicationHiddenSetting for user " + userId);
14299
14300        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
14301            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
14302            return false;
14303        }
14304
14305        long callingId = Binder.clearCallingIdentity();
14306        try {
14307            boolean sendAdded = false;
14308            boolean sendRemoved = false;
14309            // writer
14310            synchronized (mPackages) {
14311                pkgSetting = mSettings.mPackages.get(packageName);
14312                if (pkgSetting == null) {
14313                    return false;
14314                }
14315                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14316                    return false;
14317                }
14318                // Do not allow "android" is being disabled
14319                if ("android".equals(packageName)) {
14320                    Slog.w(TAG, "Cannot hide package: android");
14321                    return false;
14322                }
14323                // Cannot hide static shared libs as they are considered
14324                // a part of the using app (emulating static linking). Also
14325                // static libs are installed always on internal storage.
14326                PackageParser.Package pkg = mPackages.get(packageName);
14327                if (pkg != null && pkg.staticSharedLibName != null) {
14328                    Slog.w(TAG, "Cannot hide package: " + packageName
14329                            + " providing static shared library: "
14330                            + pkg.staticSharedLibName);
14331                    return false;
14332                }
14333                // Only allow protected packages to hide themselves.
14334                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
14335                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14336                    Slog.w(TAG, "Not hiding protected package: " + packageName);
14337                    return false;
14338                }
14339
14340                if (pkgSetting.getHidden(userId) != hidden) {
14341                    pkgSetting.setHidden(hidden, userId);
14342                    mSettings.writePackageRestrictionsLPr(userId);
14343                    if (hidden) {
14344                        sendRemoved = true;
14345                    } else {
14346                        sendAdded = true;
14347                    }
14348                }
14349            }
14350            if (sendAdded) {
14351                sendPackageAddedForUser(packageName, pkgSetting, userId);
14352                return true;
14353            }
14354            if (sendRemoved) {
14355                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
14356                        "hiding pkg");
14357                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
14358                return true;
14359            }
14360        } finally {
14361            Binder.restoreCallingIdentity(callingId);
14362        }
14363        return false;
14364    }
14365
14366    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
14367            int userId) {
14368        final PackageRemovedInfo info = new PackageRemovedInfo(this);
14369        info.removedPackage = packageName;
14370        info.installerPackageName = pkgSetting.installerPackageName;
14371        info.removedUsers = new int[] {userId};
14372        info.broadcastUsers = new int[] {userId};
14373        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
14374        info.sendPackageRemovedBroadcasts(true /*killApp*/);
14375    }
14376
14377    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
14378        if (pkgList.length > 0) {
14379            Bundle extras = new Bundle(1);
14380            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
14381
14382            sendPackageBroadcast(
14383                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
14384                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
14385                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
14386                    new int[] {userId});
14387        }
14388    }
14389
14390    /**
14391     * Returns true if application is not found or there was an error. Otherwise it returns
14392     * the hidden state of the package for the given user.
14393     */
14394    @Override
14395    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
14396        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14397        final int callingUid = Binder.getCallingUid();
14398        enforceCrossUserPermission(callingUid, userId,
14399                true /* requireFullPermission */, false /* checkShell */,
14400                "getApplicationHidden for user " + userId);
14401        PackageSetting ps;
14402        long callingId = Binder.clearCallingIdentity();
14403        try {
14404            // writer
14405            synchronized (mPackages) {
14406                ps = mSettings.mPackages.get(packageName);
14407                if (ps == null) {
14408                    return true;
14409                }
14410                if (filterAppAccessLPr(ps, callingUid, userId)) {
14411                    return true;
14412                }
14413                return ps.getHidden(userId);
14414            }
14415        } finally {
14416            Binder.restoreCallingIdentity(callingId);
14417        }
14418    }
14419
14420    /**
14421     * @hide
14422     */
14423    @Override
14424    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
14425            int installReason) {
14426        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
14427                null);
14428        PackageSetting pkgSetting;
14429        final int callingUid = Binder.getCallingUid();
14430        enforceCrossUserPermission(callingUid, userId,
14431                true /* requireFullPermission */, true /* checkShell */,
14432                "installExistingPackage for user " + userId);
14433        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14434            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
14435        }
14436
14437        long callingId = Binder.clearCallingIdentity();
14438        try {
14439            boolean installed = false;
14440            final boolean instantApp =
14441                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14442            final boolean fullApp =
14443                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
14444
14445            // writer
14446            synchronized (mPackages) {
14447                pkgSetting = mSettings.mPackages.get(packageName);
14448                if (pkgSetting == null) {
14449                    return PackageManager.INSTALL_FAILED_INVALID_URI;
14450                }
14451                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
14452                    // only allow the existing package to be used if it's installed as a full
14453                    // application for at least one user
14454                    boolean installAllowed = false;
14455                    for (int checkUserId : sUserManager.getUserIds()) {
14456                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
14457                        if (installAllowed) {
14458                            break;
14459                        }
14460                    }
14461                    if (!installAllowed) {
14462                        return PackageManager.INSTALL_FAILED_INVALID_URI;
14463                    }
14464                }
14465                if (!pkgSetting.getInstalled(userId)) {
14466                    pkgSetting.setInstalled(true, userId);
14467                    pkgSetting.setHidden(false, userId);
14468                    pkgSetting.setInstallReason(installReason, userId);
14469                    mSettings.writePackageRestrictionsLPr(userId);
14470                    mSettings.writeKernelMappingLPr(pkgSetting);
14471                    installed = true;
14472                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14473                    // upgrade app from instant to full; we don't allow app downgrade
14474                    installed = true;
14475                }
14476                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
14477            }
14478
14479            if (installed) {
14480                if (pkgSetting.pkg != null) {
14481                    synchronized (mInstallLock) {
14482                        // We don't need to freeze for a brand new install
14483                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
14484                    }
14485                }
14486                sendPackageAddedForUser(packageName, pkgSetting, userId);
14487                synchronized (mPackages) {
14488                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
14489                }
14490            }
14491        } finally {
14492            Binder.restoreCallingIdentity(callingId);
14493        }
14494
14495        return PackageManager.INSTALL_SUCCEEDED;
14496    }
14497
14498    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
14499            boolean instantApp, boolean fullApp) {
14500        // no state specified; do nothing
14501        if (!instantApp && !fullApp) {
14502            return;
14503        }
14504        if (userId != UserHandle.USER_ALL) {
14505            if (instantApp && !pkgSetting.getInstantApp(userId)) {
14506                pkgSetting.setInstantApp(true /*instantApp*/, userId);
14507            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14508                pkgSetting.setInstantApp(false /*instantApp*/, userId);
14509            }
14510        } else {
14511            for (int currentUserId : sUserManager.getUserIds()) {
14512                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
14513                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
14514                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
14515                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
14516                }
14517            }
14518        }
14519    }
14520
14521    boolean isUserRestricted(int userId, String restrictionKey) {
14522        Bundle restrictions = sUserManager.getUserRestrictions(userId);
14523        if (restrictions.getBoolean(restrictionKey, false)) {
14524            Log.w(TAG, "User is restricted: " + restrictionKey);
14525            return true;
14526        }
14527        return false;
14528    }
14529
14530    @Override
14531    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
14532            int userId) {
14533        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14534        final int callingUid = Binder.getCallingUid();
14535        enforceCrossUserPermission(callingUid, userId,
14536                true /* requireFullPermission */, true /* checkShell */,
14537                "setPackagesSuspended for user " + userId);
14538
14539        if (ArrayUtils.isEmpty(packageNames)) {
14540            return packageNames;
14541        }
14542
14543        // List of package names for whom the suspended state has changed.
14544        List<String> changedPackages = new ArrayList<>(packageNames.length);
14545        // List of package names for whom the suspended state is not set as requested in this
14546        // method.
14547        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
14548        long callingId = Binder.clearCallingIdentity();
14549        try {
14550            for (int i = 0; i < packageNames.length; i++) {
14551                String packageName = packageNames[i];
14552                boolean changed = false;
14553                final int appId;
14554                synchronized (mPackages) {
14555                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
14556                    if (pkgSetting == null
14557                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14558                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
14559                                + "\". Skipping suspending/un-suspending.");
14560                        unactionedPackages.add(packageName);
14561                        continue;
14562                    }
14563                    appId = pkgSetting.appId;
14564                    if (pkgSetting.getSuspended(userId) != suspended) {
14565                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
14566                            unactionedPackages.add(packageName);
14567                            continue;
14568                        }
14569                        pkgSetting.setSuspended(suspended, userId);
14570                        mSettings.writePackageRestrictionsLPr(userId);
14571                        changed = true;
14572                        changedPackages.add(packageName);
14573                    }
14574                }
14575
14576                if (changed && suspended) {
14577                    killApplication(packageName, UserHandle.getUid(userId, appId),
14578                            "suspending package");
14579                }
14580            }
14581        } finally {
14582            Binder.restoreCallingIdentity(callingId);
14583        }
14584
14585        if (!changedPackages.isEmpty()) {
14586            sendPackagesSuspendedForUser(changedPackages.toArray(
14587                    new String[changedPackages.size()]), userId, suspended);
14588        }
14589
14590        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
14591    }
14592
14593    @Override
14594    public boolean isPackageSuspendedForUser(String packageName, int userId) {
14595        final int callingUid = Binder.getCallingUid();
14596        enforceCrossUserPermission(callingUid, userId,
14597                true /* requireFullPermission */, false /* checkShell */,
14598                "isPackageSuspendedForUser for user " + userId);
14599        synchronized (mPackages) {
14600            final PackageSetting ps = mSettings.mPackages.get(packageName);
14601            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
14602                throw new IllegalArgumentException("Unknown target package: " + packageName);
14603            }
14604            return ps.getSuspended(userId);
14605        }
14606    }
14607
14608    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
14609        if (isPackageDeviceAdmin(packageName, userId)) {
14610            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14611                    + "\": has an active device admin");
14612            return false;
14613        }
14614
14615        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
14616        if (packageName.equals(activeLauncherPackageName)) {
14617            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14618                    + "\": contains the active launcher");
14619            return false;
14620        }
14621
14622        if (packageName.equals(mRequiredInstallerPackage)) {
14623            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14624                    + "\": required for package installation");
14625            return false;
14626        }
14627
14628        if (packageName.equals(mRequiredUninstallerPackage)) {
14629            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14630                    + "\": required for package uninstallation");
14631            return false;
14632        }
14633
14634        if (packageName.equals(mRequiredVerifierPackage)) {
14635            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14636                    + "\": required for package verification");
14637            return false;
14638        }
14639
14640        if (packageName.equals(getDefaultDialerPackageName(userId))) {
14641            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14642                    + "\": is the default dialer");
14643            return false;
14644        }
14645
14646        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14647            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14648                    + "\": protected package");
14649            return false;
14650        }
14651
14652        // Cannot suspend static shared libs as they are considered
14653        // a part of the using app (emulating static linking). Also
14654        // static libs are installed always on internal storage.
14655        PackageParser.Package pkg = mPackages.get(packageName);
14656        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
14657            Slog.w(TAG, "Cannot suspend package: " + packageName
14658                    + " providing static shared library: "
14659                    + pkg.staticSharedLibName);
14660            return false;
14661        }
14662
14663        return true;
14664    }
14665
14666    private String getActiveLauncherPackageName(int userId) {
14667        Intent intent = new Intent(Intent.ACTION_MAIN);
14668        intent.addCategory(Intent.CATEGORY_HOME);
14669        ResolveInfo resolveInfo = resolveIntent(
14670                intent,
14671                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
14672                PackageManager.MATCH_DEFAULT_ONLY,
14673                userId);
14674
14675        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
14676    }
14677
14678    private String getDefaultDialerPackageName(int userId) {
14679        synchronized (mPackages) {
14680            return mSettings.getDefaultDialerPackageNameLPw(userId);
14681        }
14682    }
14683
14684    @Override
14685    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
14686        mContext.enforceCallingOrSelfPermission(
14687                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14688                "Only package verification agents can verify applications");
14689
14690        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14691        final PackageVerificationResponse response = new PackageVerificationResponse(
14692                verificationCode, Binder.getCallingUid());
14693        msg.arg1 = id;
14694        msg.obj = response;
14695        mHandler.sendMessage(msg);
14696    }
14697
14698    @Override
14699    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
14700            long millisecondsToDelay) {
14701        mContext.enforceCallingOrSelfPermission(
14702                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14703                "Only package verification agents can extend verification timeouts");
14704
14705        final PackageVerificationState state = mPendingVerification.get(id);
14706        final PackageVerificationResponse response = new PackageVerificationResponse(
14707                verificationCodeAtTimeout, Binder.getCallingUid());
14708
14709        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
14710            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
14711        }
14712        if (millisecondsToDelay < 0) {
14713            millisecondsToDelay = 0;
14714        }
14715        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
14716                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
14717            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
14718        }
14719
14720        if ((state != null) && !state.timeoutExtended()) {
14721            state.extendTimeout();
14722
14723            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14724            msg.arg1 = id;
14725            msg.obj = response;
14726            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
14727        }
14728    }
14729
14730    private void broadcastPackageVerified(int verificationId, Uri packageUri,
14731            int verificationCode, UserHandle user) {
14732        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
14733        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
14734        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14735        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14736        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
14737
14738        mContext.sendBroadcastAsUser(intent, user,
14739                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
14740    }
14741
14742    private ComponentName matchComponentForVerifier(String packageName,
14743            List<ResolveInfo> receivers) {
14744        ActivityInfo targetReceiver = null;
14745
14746        final int NR = receivers.size();
14747        for (int i = 0; i < NR; i++) {
14748            final ResolveInfo info = receivers.get(i);
14749            if (info.activityInfo == null) {
14750                continue;
14751            }
14752
14753            if (packageName.equals(info.activityInfo.packageName)) {
14754                targetReceiver = info.activityInfo;
14755                break;
14756            }
14757        }
14758
14759        if (targetReceiver == null) {
14760            return null;
14761        }
14762
14763        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
14764    }
14765
14766    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
14767            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
14768        if (pkgInfo.verifiers.length == 0) {
14769            return null;
14770        }
14771
14772        final int N = pkgInfo.verifiers.length;
14773        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
14774        for (int i = 0; i < N; i++) {
14775            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
14776
14777            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
14778                    receivers);
14779            if (comp == null) {
14780                continue;
14781            }
14782
14783            final int verifierUid = getUidForVerifier(verifierInfo);
14784            if (verifierUid == -1) {
14785                continue;
14786            }
14787
14788            if (DEBUG_VERIFY) {
14789                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
14790                        + " with the correct signature");
14791            }
14792            sufficientVerifiers.add(comp);
14793            verificationState.addSufficientVerifier(verifierUid);
14794        }
14795
14796        return sufficientVerifiers;
14797    }
14798
14799    private int getUidForVerifier(VerifierInfo verifierInfo) {
14800        synchronized (mPackages) {
14801            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
14802            if (pkg == null) {
14803                return -1;
14804            } else if (pkg.mSignatures.length != 1) {
14805                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14806                        + " has more than one signature; ignoring");
14807                return -1;
14808            }
14809
14810            /*
14811             * If the public key of the package's signature does not match
14812             * our expected public key, then this is a different package and
14813             * we should skip.
14814             */
14815
14816            final byte[] expectedPublicKey;
14817            try {
14818                final Signature verifierSig = pkg.mSignatures[0];
14819                final PublicKey publicKey = verifierSig.getPublicKey();
14820                expectedPublicKey = publicKey.getEncoded();
14821            } catch (CertificateException e) {
14822                return -1;
14823            }
14824
14825            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
14826
14827            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
14828                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14829                        + " does not have the expected public key; ignoring");
14830                return -1;
14831            }
14832
14833            return pkg.applicationInfo.uid;
14834        }
14835    }
14836
14837    @Override
14838    public void finishPackageInstall(int token, boolean didLaunch) {
14839        enforceSystemOrRoot("Only the system is allowed to finish installs");
14840
14841        if (DEBUG_INSTALL) {
14842            Slog.v(TAG, "BM finishing package install for " + token);
14843        }
14844        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14845
14846        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
14847        mHandler.sendMessage(msg);
14848    }
14849
14850    /**
14851     * Get the verification agent timeout.  Used for both the APK verifier and the
14852     * intent filter verifier.
14853     *
14854     * @return verification timeout in milliseconds
14855     */
14856    private long getVerificationTimeout() {
14857        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
14858                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
14859                DEFAULT_VERIFICATION_TIMEOUT);
14860    }
14861
14862    /**
14863     * Get the default verification agent response code.
14864     *
14865     * @return default verification response code
14866     */
14867    private int getDefaultVerificationResponse(UserHandle user) {
14868        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
14869            return PackageManager.VERIFICATION_REJECT;
14870        }
14871        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14872                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
14873                DEFAULT_VERIFICATION_RESPONSE);
14874    }
14875
14876    /**
14877     * Check whether or not package verification has been enabled.
14878     *
14879     * @return true if verification should be performed
14880     */
14881    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
14882        if (!DEFAULT_VERIFY_ENABLE) {
14883            return false;
14884        }
14885
14886        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
14887
14888        // Check if installing from ADB
14889        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
14890            // Do not run verification in a test harness environment
14891            if (ActivityManager.isRunningInTestHarness()) {
14892                return false;
14893            }
14894            if (ensureVerifyAppsEnabled) {
14895                return true;
14896            }
14897            // Check if the developer does not want package verification for ADB installs
14898            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14899                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
14900                return false;
14901            }
14902        } else {
14903            // only when not installed from ADB, skip verification for instant apps when
14904            // the installer and verifier are the same.
14905            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14906                if (mInstantAppInstallerActivity != null
14907                        && mInstantAppInstallerActivity.packageName.equals(
14908                                mRequiredVerifierPackage)) {
14909                    try {
14910                        mContext.getSystemService(AppOpsManager.class)
14911                                .checkPackage(installerUid, mRequiredVerifierPackage);
14912                        if (DEBUG_VERIFY) {
14913                            Slog.i(TAG, "disable verification for instant app");
14914                        }
14915                        return false;
14916                    } catch (SecurityException ignore) { }
14917                }
14918            }
14919        }
14920
14921        if (ensureVerifyAppsEnabled) {
14922            return true;
14923        }
14924
14925        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14926                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
14927    }
14928
14929    @Override
14930    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
14931            throws RemoteException {
14932        mContext.enforceCallingOrSelfPermission(
14933                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
14934                "Only intentfilter verification agents can verify applications");
14935
14936        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
14937        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
14938                Binder.getCallingUid(), verificationCode, failedDomains);
14939        msg.arg1 = id;
14940        msg.obj = response;
14941        mHandler.sendMessage(msg);
14942    }
14943
14944    @Override
14945    public int getIntentVerificationStatus(String packageName, int userId) {
14946        final int callingUid = Binder.getCallingUid();
14947        if (getInstantAppPackageName(callingUid) != null) {
14948            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14949        }
14950        synchronized (mPackages) {
14951            final PackageSetting ps = mSettings.mPackages.get(packageName);
14952            if (ps == null
14953                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14954                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14955            }
14956            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
14957        }
14958    }
14959
14960    @Override
14961    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
14962        mContext.enforceCallingOrSelfPermission(
14963                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14964
14965        boolean result = false;
14966        synchronized (mPackages) {
14967            final PackageSetting ps = mSettings.mPackages.get(packageName);
14968            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
14969                return false;
14970            }
14971            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
14972        }
14973        if (result) {
14974            scheduleWritePackageRestrictionsLocked(userId);
14975        }
14976        return result;
14977    }
14978
14979    @Override
14980    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
14981            String packageName) {
14982        final int callingUid = Binder.getCallingUid();
14983        if (getInstantAppPackageName(callingUid) != null) {
14984            return ParceledListSlice.emptyList();
14985        }
14986        synchronized (mPackages) {
14987            final PackageSetting ps = mSettings.mPackages.get(packageName);
14988            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14989                return ParceledListSlice.emptyList();
14990            }
14991            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
14992        }
14993    }
14994
14995    @Override
14996    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
14997        if (TextUtils.isEmpty(packageName)) {
14998            return ParceledListSlice.emptyList();
14999        }
15000        final int callingUid = Binder.getCallingUid();
15001        final int callingUserId = UserHandle.getUserId(callingUid);
15002        synchronized (mPackages) {
15003            PackageParser.Package pkg = mPackages.get(packageName);
15004            if (pkg == null || pkg.activities == null) {
15005                return ParceledListSlice.emptyList();
15006            }
15007            if (pkg.mExtras == null) {
15008                return ParceledListSlice.emptyList();
15009            }
15010            final PackageSetting ps = (PackageSetting) pkg.mExtras;
15011            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
15012                return ParceledListSlice.emptyList();
15013            }
15014            final int count = pkg.activities.size();
15015            ArrayList<IntentFilter> result = new ArrayList<>();
15016            for (int n=0; n<count; n++) {
15017                PackageParser.Activity activity = pkg.activities.get(n);
15018                if (activity.intents != null && activity.intents.size() > 0) {
15019                    result.addAll(activity.intents);
15020                }
15021            }
15022            return new ParceledListSlice<>(result);
15023        }
15024    }
15025
15026    @Override
15027    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
15028        mContext.enforceCallingOrSelfPermission(
15029                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15030
15031        synchronized (mPackages) {
15032            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
15033            if (packageName != null) {
15034                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
15035                        packageName, userId);
15036            }
15037            return result;
15038        }
15039    }
15040
15041    @Override
15042    public String getDefaultBrowserPackageName(int userId) {
15043        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15044            return null;
15045        }
15046        synchronized (mPackages) {
15047            return mSettings.getDefaultBrowserPackageNameLPw(userId);
15048        }
15049    }
15050
15051    /**
15052     * Get the "allow unknown sources" setting.
15053     *
15054     * @return the current "allow unknown sources" setting
15055     */
15056    private int getUnknownSourcesSettings() {
15057        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
15058                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
15059                -1);
15060    }
15061
15062    @Override
15063    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
15064        final int callingUid = Binder.getCallingUid();
15065        if (getInstantAppPackageName(callingUid) != null) {
15066            return;
15067        }
15068        // writer
15069        synchronized (mPackages) {
15070            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
15071            if (targetPackageSetting == null
15072                    || filterAppAccessLPr(
15073                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
15074                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
15075            }
15076
15077            PackageSetting installerPackageSetting;
15078            if (installerPackageName != null) {
15079                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
15080                if (installerPackageSetting == null) {
15081                    throw new IllegalArgumentException("Unknown installer package: "
15082                            + installerPackageName);
15083                }
15084            } else {
15085                installerPackageSetting = null;
15086            }
15087
15088            Signature[] callerSignature;
15089            Object obj = mSettings.getUserIdLPr(callingUid);
15090            if (obj != null) {
15091                if (obj instanceof SharedUserSetting) {
15092                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
15093                } else if (obj instanceof PackageSetting) {
15094                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
15095                } else {
15096                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
15097                }
15098            } else {
15099                throw new SecurityException("Unknown calling UID: " + callingUid);
15100            }
15101
15102            // Verify: can't set installerPackageName to a package that is
15103            // not signed with the same cert as the caller.
15104            if (installerPackageSetting != null) {
15105                if (compareSignatures(callerSignature,
15106                        installerPackageSetting.signatures.mSignatures)
15107                        != PackageManager.SIGNATURE_MATCH) {
15108                    throw new SecurityException(
15109                            "Caller does not have same cert as new installer package "
15110                            + installerPackageName);
15111                }
15112            }
15113
15114            // Verify: if target already has an installer package, it must
15115            // be signed with the same cert as the caller.
15116            if (targetPackageSetting.installerPackageName != null) {
15117                PackageSetting setting = mSettings.mPackages.get(
15118                        targetPackageSetting.installerPackageName);
15119                // If the currently set package isn't valid, then it's always
15120                // okay to change it.
15121                if (setting != null) {
15122                    if (compareSignatures(callerSignature,
15123                            setting.signatures.mSignatures)
15124                            != PackageManager.SIGNATURE_MATCH) {
15125                        throw new SecurityException(
15126                                "Caller does not have same cert as old installer package "
15127                                + targetPackageSetting.installerPackageName);
15128                    }
15129                }
15130            }
15131
15132            // Okay!
15133            targetPackageSetting.installerPackageName = installerPackageName;
15134            if (installerPackageName != null) {
15135                mSettings.mInstallerPackages.add(installerPackageName);
15136            }
15137            scheduleWriteSettingsLocked();
15138        }
15139    }
15140
15141    @Override
15142    public void setApplicationCategoryHint(String packageName, int categoryHint,
15143            String callerPackageName) {
15144        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15145            throw new SecurityException("Instant applications don't have access to this method");
15146        }
15147        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
15148                callerPackageName);
15149        synchronized (mPackages) {
15150            PackageSetting ps = mSettings.mPackages.get(packageName);
15151            if (ps == null) {
15152                throw new IllegalArgumentException("Unknown target package " + packageName);
15153            }
15154            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15155                throw new IllegalArgumentException("Unknown target package " + packageName);
15156            }
15157            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
15158                throw new IllegalArgumentException("Calling package " + callerPackageName
15159                        + " is not installer for " + packageName);
15160            }
15161
15162            if (ps.categoryHint != categoryHint) {
15163                ps.categoryHint = categoryHint;
15164                scheduleWriteSettingsLocked();
15165            }
15166        }
15167    }
15168
15169    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
15170        // Queue up an async operation since the package installation may take a little while.
15171        mHandler.post(new Runnable() {
15172            public void run() {
15173                mHandler.removeCallbacks(this);
15174                 // Result object to be returned
15175                PackageInstalledInfo res = new PackageInstalledInfo();
15176                res.setReturnCode(currentStatus);
15177                res.uid = -1;
15178                res.pkg = null;
15179                res.removedInfo = null;
15180                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15181                    args.doPreInstall(res.returnCode);
15182                    synchronized (mInstallLock) {
15183                        installPackageTracedLI(args, res);
15184                    }
15185                    args.doPostInstall(res.returnCode, res.uid);
15186                }
15187
15188                // A restore should be performed at this point if (a) the install
15189                // succeeded, (b) the operation is not an update, and (c) the new
15190                // package has not opted out of backup participation.
15191                final boolean update = res.removedInfo != null
15192                        && res.removedInfo.removedPackage != null;
15193                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
15194                boolean doRestore = !update
15195                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
15196
15197                // Set up the post-install work request bookkeeping.  This will be used
15198                // and cleaned up by the post-install event handling regardless of whether
15199                // there's a restore pass performed.  Token values are >= 1.
15200                int token;
15201                if (mNextInstallToken < 0) mNextInstallToken = 1;
15202                token = mNextInstallToken++;
15203
15204                PostInstallData data = new PostInstallData(args, res);
15205                mRunningInstalls.put(token, data);
15206                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
15207
15208                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
15209                    // Pass responsibility to the Backup Manager.  It will perform a
15210                    // restore if appropriate, then pass responsibility back to the
15211                    // Package Manager to run the post-install observer callbacks
15212                    // and broadcasts.
15213                    IBackupManager bm = IBackupManager.Stub.asInterface(
15214                            ServiceManager.getService(Context.BACKUP_SERVICE));
15215                    if (bm != null) {
15216                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
15217                                + " to BM for possible restore");
15218                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
15219                        try {
15220                            // TODO: http://b/22388012
15221                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
15222                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
15223                            } else {
15224                                doRestore = false;
15225                            }
15226                        } catch (RemoteException e) {
15227                            // can't happen; the backup manager is local
15228                        } catch (Exception e) {
15229                            Slog.e(TAG, "Exception trying to enqueue restore", e);
15230                            doRestore = false;
15231                        }
15232                    } else {
15233                        Slog.e(TAG, "Backup Manager not found!");
15234                        doRestore = false;
15235                    }
15236                }
15237
15238                if (!doRestore) {
15239                    // No restore possible, or the Backup Manager was mysteriously not
15240                    // available -- just fire the post-install work request directly.
15241                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
15242
15243                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
15244
15245                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
15246                    mHandler.sendMessage(msg);
15247                }
15248            }
15249        });
15250    }
15251
15252    /**
15253     * Callback from PackageSettings whenever an app is first transitioned out of the
15254     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
15255     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
15256     * here whether the app is the target of an ongoing install, and only send the
15257     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
15258     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
15259     * handling.
15260     */
15261    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
15262        // Serialize this with the rest of the install-process message chain.  In the
15263        // restore-at-install case, this Runnable will necessarily run before the
15264        // POST_INSTALL message is processed, so the contents of mRunningInstalls
15265        // are coherent.  In the non-restore case, the app has already completed install
15266        // and been launched through some other means, so it is not in a problematic
15267        // state for observers to see the FIRST_LAUNCH signal.
15268        mHandler.post(new Runnable() {
15269            @Override
15270            public void run() {
15271                for (int i = 0; i < mRunningInstalls.size(); i++) {
15272                    final PostInstallData data = mRunningInstalls.valueAt(i);
15273                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15274                        continue;
15275                    }
15276                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
15277                        // right package; but is it for the right user?
15278                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
15279                            if (userId == data.res.newUsers[uIndex]) {
15280                                if (DEBUG_BACKUP) {
15281                                    Slog.i(TAG, "Package " + pkgName
15282                                            + " being restored so deferring FIRST_LAUNCH");
15283                                }
15284                                return;
15285                            }
15286                        }
15287                    }
15288                }
15289                // didn't find it, so not being restored
15290                if (DEBUG_BACKUP) {
15291                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
15292                }
15293                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
15294            }
15295        });
15296    }
15297
15298    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
15299        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
15300                installerPkg, null, userIds);
15301    }
15302
15303    private abstract class HandlerParams {
15304        private static final int MAX_RETRIES = 4;
15305
15306        /**
15307         * Number of times startCopy() has been attempted and had a non-fatal
15308         * error.
15309         */
15310        private int mRetries = 0;
15311
15312        /** User handle for the user requesting the information or installation. */
15313        private final UserHandle mUser;
15314        String traceMethod;
15315        int traceCookie;
15316
15317        HandlerParams(UserHandle user) {
15318            mUser = user;
15319        }
15320
15321        UserHandle getUser() {
15322            return mUser;
15323        }
15324
15325        HandlerParams setTraceMethod(String traceMethod) {
15326            this.traceMethod = traceMethod;
15327            return this;
15328        }
15329
15330        HandlerParams setTraceCookie(int traceCookie) {
15331            this.traceCookie = traceCookie;
15332            return this;
15333        }
15334
15335        final boolean startCopy() {
15336            boolean res;
15337            try {
15338                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
15339
15340                if (++mRetries > MAX_RETRIES) {
15341                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
15342                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
15343                    handleServiceError();
15344                    return false;
15345                } else {
15346                    handleStartCopy();
15347                    res = true;
15348                }
15349            } catch (RemoteException e) {
15350                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
15351                mHandler.sendEmptyMessage(MCS_RECONNECT);
15352                res = false;
15353            }
15354            handleReturnCode();
15355            return res;
15356        }
15357
15358        final void serviceError() {
15359            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
15360            handleServiceError();
15361            handleReturnCode();
15362        }
15363
15364        abstract void handleStartCopy() throws RemoteException;
15365        abstract void handleServiceError();
15366        abstract void handleReturnCode();
15367    }
15368
15369    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
15370        for (File path : paths) {
15371            try {
15372                mcs.clearDirectory(path.getAbsolutePath());
15373            } catch (RemoteException e) {
15374            }
15375        }
15376    }
15377
15378    static class OriginInfo {
15379        /**
15380         * Location where install is coming from, before it has been
15381         * copied/renamed into place. This could be a single monolithic APK
15382         * file, or a cluster directory. This location may be untrusted.
15383         */
15384        final File file;
15385        final String cid;
15386
15387        /**
15388         * Flag indicating that {@link #file} or {@link #cid} has already been
15389         * staged, meaning downstream users don't need to defensively copy the
15390         * contents.
15391         */
15392        final boolean staged;
15393
15394        /**
15395         * Flag indicating that {@link #file} or {@link #cid} is an already
15396         * installed app that is being moved.
15397         */
15398        final boolean existing;
15399
15400        final String resolvedPath;
15401        final File resolvedFile;
15402
15403        static OriginInfo fromNothing() {
15404            return new OriginInfo(null, null, false, false);
15405        }
15406
15407        static OriginInfo fromUntrustedFile(File file) {
15408            return new OriginInfo(file, null, false, false);
15409        }
15410
15411        static OriginInfo fromExistingFile(File file) {
15412            return new OriginInfo(file, null, false, true);
15413        }
15414
15415        static OriginInfo fromStagedFile(File file) {
15416            return new OriginInfo(file, null, true, false);
15417        }
15418
15419        static OriginInfo fromStagedContainer(String cid) {
15420            return new OriginInfo(null, cid, true, false);
15421        }
15422
15423        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
15424            this.file = file;
15425            this.cid = cid;
15426            this.staged = staged;
15427            this.existing = existing;
15428
15429            if (cid != null) {
15430                resolvedPath = PackageHelper.getSdDir(cid);
15431                resolvedFile = new File(resolvedPath);
15432            } else if (file != null) {
15433                resolvedPath = file.getAbsolutePath();
15434                resolvedFile = file;
15435            } else {
15436                resolvedPath = null;
15437                resolvedFile = null;
15438            }
15439        }
15440    }
15441
15442    static class MoveInfo {
15443        final int moveId;
15444        final String fromUuid;
15445        final String toUuid;
15446        final String packageName;
15447        final String dataAppName;
15448        final int appId;
15449        final String seinfo;
15450        final int targetSdkVersion;
15451
15452        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
15453                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
15454            this.moveId = moveId;
15455            this.fromUuid = fromUuid;
15456            this.toUuid = toUuid;
15457            this.packageName = packageName;
15458            this.dataAppName = dataAppName;
15459            this.appId = appId;
15460            this.seinfo = seinfo;
15461            this.targetSdkVersion = targetSdkVersion;
15462        }
15463    }
15464
15465    static class VerificationInfo {
15466        /** A constant used to indicate that a uid value is not present. */
15467        public static final int NO_UID = -1;
15468
15469        /** URI referencing where the package was downloaded from. */
15470        final Uri originatingUri;
15471
15472        /** HTTP referrer URI associated with the originatingURI. */
15473        final Uri referrer;
15474
15475        /** UID of the application that the install request originated from. */
15476        final int originatingUid;
15477
15478        /** UID of application requesting the install */
15479        final int installerUid;
15480
15481        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
15482            this.originatingUri = originatingUri;
15483            this.referrer = referrer;
15484            this.originatingUid = originatingUid;
15485            this.installerUid = installerUid;
15486        }
15487    }
15488
15489    class InstallParams extends HandlerParams {
15490        final OriginInfo origin;
15491        final MoveInfo move;
15492        final IPackageInstallObserver2 observer;
15493        int installFlags;
15494        final String installerPackageName;
15495        final String volumeUuid;
15496        private InstallArgs mArgs;
15497        private int mRet;
15498        final String packageAbiOverride;
15499        final String[] grantedRuntimePermissions;
15500        final VerificationInfo verificationInfo;
15501        final Certificate[][] certificates;
15502        final int installReason;
15503
15504        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15505                int installFlags, String installerPackageName, String volumeUuid,
15506                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
15507                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
15508            super(user);
15509            this.origin = origin;
15510            this.move = move;
15511            this.observer = observer;
15512            this.installFlags = installFlags;
15513            this.installerPackageName = installerPackageName;
15514            this.volumeUuid = volumeUuid;
15515            this.verificationInfo = verificationInfo;
15516            this.packageAbiOverride = packageAbiOverride;
15517            this.grantedRuntimePermissions = grantedPermissions;
15518            this.certificates = certificates;
15519            this.installReason = installReason;
15520        }
15521
15522        @Override
15523        public String toString() {
15524            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
15525                    + " file=" + origin.file + " cid=" + origin.cid + "}";
15526        }
15527
15528        private int installLocationPolicy(PackageInfoLite pkgLite) {
15529            String packageName = pkgLite.packageName;
15530            int installLocation = pkgLite.installLocation;
15531            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15532            // reader
15533            synchronized (mPackages) {
15534                // Currently installed package which the new package is attempting to replace or
15535                // null if no such package is installed.
15536                PackageParser.Package installedPkg = mPackages.get(packageName);
15537                // Package which currently owns the data which the new package will own if installed.
15538                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
15539                // will be null whereas dataOwnerPkg will contain information about the package
15540                // which was uninstalled while keeping its data.
15541                PackageParser.Package dataOwnerPkg = installedPkg;
15542                if (dataOwnerPkg  == null) {
15543                    PackageSetting ps = mSettings.mPackages.get(packageName);
15544                    if (ps != null) {
15545                        dataOwnerPkg = ps.pkg;
15546                    }
15547                }
15548
15549                if (dataOwnerPkg != null) {
15550                    // If installed, the package will get access to data left on the device by its
15551                    // predecessor. As a security measure, this is permited only if this is not a
15552                    // version downgrade or if the predecessor package is marked as debuggable and
15553                    // a downgrade is explicitly requested.
15554                    //
15555                    // On debuggable platform builds, downgrades are permitted even for
15556                    // non-debuggable packages to make testing easier. Debuggable platform builds do
15557                    // not offer security guarantees and thus it's OK to disable some security
15558                    // mechanisms to make debugging/testing easier on those builds. However, even on
15559                    // debuggable builds downgrades of packages are permitted only if requested via
15560                    // installFlags. This is because we aim to keep the behavior of debuggable
15561                    // platform builds as close as possible to the behavior of non-debuggable
15562                    // platform builds.
15563                    final boolean downgradeRequested =
15564                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
15565                    final boolean packageDebuggable =
15566                                (dataOwnerPkg.applicationInfo.flags
15567                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
15568                    final boolean downgradePermitted =
15569                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
15570                    if (!downgradePermitted) {
15571                        try {
15572                            checkDowngrade(dataOwnerPkg, pkgLite);
15573                        } catch (PackageManagerException e) {
15574                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
15575                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
15576                        }
15577                    }
15578                }
15579
15580                if (installedPkg != null) {
15581                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15582                        // Check for updated system application.
15583                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15584                            if (onSd) {
15585                                Slog.w(TAG, "Cannot install update to system app on sdcard");
15586                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
15587                            }
15588                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15589                        } else {
15590                            if (onSd) {
15591                                // Install flag overrides everything.
15592                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15593                            }
15594                            // If current upgrade specifies particular preference
15595                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
15596                                // Application explicitly specified internal.
15597                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15598                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
15599                                // App explictly prefers external. Let policy decide
15600                            } else {
15601                                // Prefer previous location
15602                                if (isExternal(installedPkg)) {
15603                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15604                                }
15605                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15606                            }
15607                        }
15608                    } else {
15609                        // Invalid install. Return error code
15610                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
15611                    }
15612                }
15613            }
15614            // All the special cases have been taken care of.
15615            // Return result based on recommended install location.
15616            if (onSd) {
15617                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15618            }
15619            return pkgLite.recommendedInstallLocation;
15620        }
15621
15622        /*
15623         * Invoke remote method to get package information and install
15624         * location values. Override install location based on default
15625         * policy if needed and then create install arguments based
15626         * on the install location.
15627         */
15628        public void handleStartCopy() throws RemoteException {
15629            int ret = PackageManager.INSTALL_SUCCEEDED;
15630
15631            // If we're already staged, we've firmly committed to an install location
15632            if (origin.staged) {
15633                if (origin.file != null) {
15634                    installFlags |= PackageManager.INSTALL_INTERNAL;
15635                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15636                } else if (origin.cid != null) {
15637                    installFlags |= PackageManager.INSTALL_EXTERNAL;
15638                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
15639                } else {
15640                    throw new IllegalStateException("Invalid stage location");
15641                }
15642            }
15643
15644            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15645            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
15646            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15647            PackageInfoLite pkgLite = null;
15648
15649            if (onInt && onSd) {
15650                // Check if both bits are set.
15651                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
15652                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15653            } else if (onSd && ephemeral) {
15654                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
15655                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15656            } else {
15657                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
15658                        packageAbiOverride);
15659
15660                if (DEBUG_EPHEMERAL && ephemeral) {
15661                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
15662                }
15663
15664                /*
15665                 * If we have too little free space, try to free cache
15666                 * before giving up.
15667                 */
15668                if (!origin.staged && pkgLite.recommendedInstallLocation
15669                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15670                    // TODO: focus freeing disk space on the target device
15671                    final StorageManager storage = StorageManager.from(mContext);
15672                    final long lowThreshold = storage.getStorageLowBytes(
15673                            Environment.getDataDirectory());
15674
15675                    final long sizeBytes = mContainerService.calculateInstalledSize(
15676                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
15677
15678                    try {
15679                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
15680                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
15681                                installFlags, packageAbiOverride);
15682                    } catch (InstallerException e) {
15683                        Slog.w(TAG, "Failed to free cache", e);
15684                    }
15685
15686                    /*
15687                     * The cache free must have deleted the file we
15688                     * downloaded to install.
15689                     *
15690                     * TODO: fix the "freeCache" call to not delete
15691                     *       the file we care about.
15692                     */
15693                    if (pkgLite.recommendedInstallLocation
15694                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15695                        pkgLite.recommendedInstallLocation
15696                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
15697                    }
15698                }
15699            }
15700
15701            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15702                int loc = pkgLite.recommendedInstallLocation;
15703                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
15704                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15705                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
15706                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
15707                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15708                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15709                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
15710                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
15711                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15712                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
15713                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
15714                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
15715                } else {
15716                    // Override with defaults if needed.
15717                    loc = installLocationPolicy(pkgLite);
15718                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
15719                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
15720                    } else if (!onSd && !onInt) {
15721                        // Override install location with flags
15722                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
15723                            // Set the flag to install on external media.
15724                            installFlags |= PackageManager.INSTALL_EXTERNAL;
15725                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
15726                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
15727                            if (DEBUG_EPHEMERAL) {
15728                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
15729                            }
15730                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
15731                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
15732                                    |PackageManager.INSTALL_INTERNAL);
15733                        } else {
15734                            // Make sure the flag for installing on external
15735                            // media is unset
15736                            installFlags |= PackageManager.INSTALL_INTERNAL;
15737                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15738                        }
15739                    }
15740                }
15741            }
15742
15743            final InstallArgs args = createInstallArgs(this);
15744            mArgs = args;
15745
15746            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15747                // TODO: http://b/22976637
15748                // Apps installed for "all" users use the device owner to verify the app
15749                UserHandle verifierUser = getUser();
15750                if (verifierUser == UserHandle.ALL) {
15751                    verifierUser = UserHandle.SYSTEM;
15752                }
15753
15754                /*
15755                 * Determine if we have any installed package verifiers. If we
15756                 * do, then we'll defer to them to verify the packages.
15757                 */
15758                final int requiredUid = mRequiredVerifierPackage == null ? -1
15759                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15760                                verifierUser.getIdentifier());
15761                final int installerUid =
15762                        verificationInfo == null ? -1 : verificationInfo.installerUid;
15763                if (!origin.existing && requiredUid != -1
15764                        && isVerificationEnabled(
15765                                verifierUser.getIdentifier(), installFlags, installerUid)) {
15766                    final Intent verification = new Intent(
15767                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
15768                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
15769                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
15770                            PACKAGE_MIME_TYPE);
15771                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15772
15773                    // Query all live verifiers based on current user state
15774                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
15775                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
15776
15777                    if (DEBUG_VERIFY) {
15778                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
15779                                + verification.toString() + " with " + pkgLite.verifiers.length
15780                                + " optional verifiers");
15781                    }
15782
15783                    final int verificationId = mPendingVerificationToken++;
15784
15785                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15786
15787                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
15788                            installerPackageName);
15789
15790                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
15791                            installFlags);
15792
15793                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
15794                            pkgLite.packageName);
15795
15796                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
15797                            pkgLite.versionCode);
15798
15799                    if (verificationInfo != null) {
15800                        if (verificationInfo.originatingUri != null) {
15801                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
15802                                    verificationInfo.originatingUri);
15803                        }
15804                        if (verificationInfo.referrer != null) {
15805                            verification.putExtra(Intent.EXTRA_REFERRER,
15806                                    verificationInfo.referrer);
15807                        }
15808                        if (verificationInfo.originatingUid >= 0) {
15809                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
15810                                    verificationInfo.originatingUid);
15811                        }
15812                        if (verificationInfo.installerUid >= 0) {
15813                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
15814                                    verificationInfo.installerUid);
15815                        }
15816                    }
15817
15818                    final PackageVerificationState verificationState = new PackageVerificationState(
15819                            requiredUid, args);
15820
15821                    mPendingVerification.append(verificationId, verificationState);
15822
15823                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
15824                            receivers, verificationState);
15825
15826                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
15827                    final long idleDuration = getVerificationTimeout();
15828
15829                    /*
15830                     * If any sufficient verifiers were listed in the package
15831                     * manifest, attempt to ask them.
15832                     */
15833                    if (sufficientVerifiers != null) {
15834                        final int N = sufficientVerifiers.size();
15835                        if (N == 0) {
15836                            Slog.i(TAG, "Additional verifiers required, but none installed.");
15837                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
15838                        } else {
15839                            for (int i = 0; i < N; i++) {
15840                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
15841                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15842                                        verifierComponent.getPackageName(), idleDuration,
15843                                        verifierUser.getIdentifier(), false, "package verifier");
15844
15845                                final Intent sufficientIntent = new Intent(verification);
15846                                sufficientIntent.setComponent(verifierComponent);
15847                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
15848                            }
15849                        }
15850                    }
15851
15852                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
15853                            mRequiredVerifierPackage, receivers);
15854                    if (ret == PackageManager.INSTALL_SUCCEEDED
15855                            && mRequiredVerifierPackage != null) {
15856                        Trace.asyncTraceBegin(
15857                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
15858                        /*
15859                         * Send the intent to the required verification agent,
15860                         * but only start the verification timeout after the
15861                         * target BroadcastReceivers have run.
15862                         */
15863                        verification.setComponent(requiredVerifierComponent);
15864                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15865                                mRequiredVerifierPackage, idleDuration,
15866                                verifierUser.getIdentifier(), false, "package verifier");
15867                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
15868                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15869                                new BroadcastReceiver() {
15870                                    @Override
15871                                    public void onReceive(Context context, Intent intent) {
15872                                        final Message msg = mHandler
15873                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
15874                                        msg.arg1 = verificationId;
15875                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
15876                                    }
15877                                }, null, 0, null, null);
15878
15879                        /*
15880                         * We don't want the copy to proceed until verification
15881                         * succeeds, so null out this field.
15882                         */
15883                        mArgs = null;
15884                    }
15885                } else {
15886                    /*
15887                     * No package verification is enabled, so immediately start
15888                     * the remote call to initiate copy using temporary file.
15889                     */
15890                    ret = args.copyApk(mContainerService, true);
15891                }
15892            }
15893
15894            mRet = ret;
15895        }
15896
15897        @Override
15898        void handleReturnCode() {
15899            // If mArgs is null, then MCS couldn't be reached. When it
15900            // reconnects, it will try again to install. At that point, this
15901            // will succeed.
15902            if (mArgs != null) {
15903                processPendingInstall(mArgs, mRet);
15904            }
15905        }
15906
15907        @Override
15908        void handleServiceError() {
15909            mArgs = createInstallArgs(this);
15910            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15911        }
15912
15913        public boolean isForwardLocked() {
15914            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15915        }
15916    }
15917
15918    /**
15919     * Used during creation of InstallArgs
15920     *
15921     * @param installFlags package installation flags
15922     * @return true if should be installed on external storage
15923     */
15924    private static boolean installOnExternalAsec(int installFlags) {
15925        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
15926            return false;
15927        }
15928        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
15929            return true;
15930        }
15931        return false;
15932    }
15933
15934    /**
15935     * Used during creation of InstallArgs
15936     *
15937     * @param installFlags package installation flags
15938     * @return true if should be installed as forward locked
15939     */
15940    private static boolean installForwardLocked(int installFlags) {
15941        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15942    }
15943
15944    private InstallArgs createInstallArgs(InstallParams params) {
15945        if (params.move != null) {
15946            return new MoveInstallArgs(params);
15947        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
15948            return new AsecInstallArgs(params);
15949        } else {
15950            return new FileInstallArgs(params);
15951        }
15952    }
15953
15954    /**
15955     * Create args that describe an existing installed package. Typically used
15956     * when cleaning up old installs, or used as a move source.
15957     */
15958    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
15959            String resourcePath, String[] instructionSets) {
15960        final boolean isInAsec;
15961        if (installOnExternalAsec(installFlags)) {
15962            /* Apps on SD card are always in ASEC containers. */
15963            isInAsec = true;
15964        } else if (installForwardLocked(installFlags)
15965                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
15966            /*
15967             * Forward-locked apps are only in ASEC containers if they're the
15968             * new style
15969             */
15970            isInAsec = true;
15971        } else {
15972            isInAsec = false;
15973        }
15974
15975        if (isInAsec) {
15976            return new AsecInstallArgs(codePath, instructionSets,
15977                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
15978        } else {
15979            return new FileInstallArgs(codePath, resourcePath, instructionSets);
15980        }
15981    }
15982
15983    static abstract class InstallArgs {
15984        /** @see InstallParams#origin */
15985        final OriginInfo origin;
15986        /** @see InstallParams#move */
15987        final MoveInfo move;
15988
15989        final IPackageInstallObserver2 observer;
15990        // Always refers to PackageManager flags only
15991        final int installFlags;
15992        final String installerPackageName;
15993        final String volumeUuid;
15994        final UserHandle user;
15995        final String abiOverride;
15996        final String[] installGrantPermissions;
15997        /** If non-null, drop an async trace when the install completes */
15998        final String traceMethod;
15999        final int traceCookie;
16000        final Certificate[][] certificates;
16001        final int installReason;
16002
16003        // The list of instruction sets supported by this app. This is currently
16004        // only used during the rmdex() phase to clean up resources. We can get rid of this
16005        // if we move dex files under the common app path.
16006        /* nullable */ String[] instructionSets;
16007
16008        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
16009                int installFlags, String installerPackageName, String volumeUuid,
16010                UserHandle user, String[] instructionSets,
16011                String abiOverride, String[] installGrantPermissions,
16012                String traceMethod, int traceCookie, Certificate[][] certificates,
16013                int installReason) {
16014            this.origin = origin;
16015            this.move = move;
16016            this.installFlags = installFlags;
16017            this.observer = observer;
16018            this.installerPackageName = installerPackageName;
16019            this.volumeUuid = volumeUuid;
16020            this.user = user;
16021            this.instructionSets = instructionSets;
16022            this.abiOverride = abiOverride;
16023            this.installGrantPermissions = installGrantPermissions;
16024            this.traceMethod = traceMethod;
16025            this.traceCookie = traceCookie;
16026            this.certificates = certificates;
16027            this.installReason = installReason;
16028        }
16029
16030        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
16031        abstract int doPreInstall(int status);
16032
16033        /**
16034         * Rename package into final resting place. All paths on the given
16035         * scanned package should be updated to reflect the rename.
16036         */
16037        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
16038        abstract int doPostInstall(int status, int uid);
16039
16040        /** @see PackageSettingBase#codePathString */
16041        abstract String getCodePath();
16042        /** @see PackageSettingBase#resourcePathString */
16043        abstract String getResourcePath();
16044
16045        // Need installer lock especially for dex file removal.
16046        abstract void cleanUpResourcesLI();
16047        abstract boolean doPostDeleteLI(boolean delete);
16048
16049        /**
16050         * Called before the source arguments are copied. This is used mostly
16051         * for MoveParams when it needs to read the source file to put it in the
16052         * destination.
16053         */
16054        int doPreCopy() {
16055            return PackageManager.INSTALL_SUCCEEDED;
16056        }
16057
16058        /**
16059         * Called after the source arguments are copied. This is used mostly for
16060         * MoveParams when it needs to read the source file to put it in the
16061         * destination.
16062         */
16063        int doPostCopy(int uid) {
16064            return PackageManager.INSTALL_SUCCEEDED;
16065        }
16066
16067        protected boolean isFwdLocked() {
16068            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16069        }
16070
16071        protected boolean isExternalAsec() {
16072            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16073        }
16074
16075        protected boolean isEphemeral() {
16076            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16077        }
16078
16079        UserHandle getUser() {
16080            return user;
16081        }
16082    }
16083
16084    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
16085        if (!allCodePaths.isEmpty()) {
16086            if (instructionSets == null) {
16087                throw new IllegalStateException("instructionSet == null");
16088            }
16089            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
16090            for (String codePath : allCodePaths) {
16091                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
16092                    try {
16093                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
16094                    } catch (InstallerException ignored) {
16095                    }
16096                }
16097            }
16098        }
16099    }
16100
16101    /**
16102     * Logic to handle installation of non-ASEC applications, including copying
16103     * and renaming logic.
16104     */
16105    class FileInstallArgs extends InstallArgs {
16106        private File codeFile;
16107        private File resourceFile;
16108
16109        // Example topology:
16110        // /data/app/com.example/base.apk
16111        // /data/app/com.example/split_foo.apk
16112        // /data/app/com.example/lib/arm/libfoo.so
16113        // /data/app/com.example/lib/arm64/libfoo.so
16114        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
16115
16116        /** New install */
16117        FileInstallArgs(InstallParams params) {
16118            super(params.origin, params.move, params.observer, params.installFlags,
16119                    params.installerPackageName, params.volumeUuid,
16120                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
16121                    params.grantedRuntimePermissions,
16122                    params.traceMethod, params.traceCookie, params.certificates,
16123                    params.installReason);
16124            if (isFwdLocked()) {
16125                throw new IllegalArgumentException("Forward locking only supported in ASEC");
16126            }
16127        }
16128
16129        /** Existing install */
16130        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
16131            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
16132                    null, null, null, 0, null /*certificates*/,
16133                    PackageManager.INSTALL_REASON_UNKNOWN);
16134            this.codeFile = (codePath != null) ? new File(codePath) : null;
16135            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
16136        }
16137
16138        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16139            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
16140            try {
16141                return doCopyApk(imcs, temp);
16142            } finally {
16143                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16144            }
16145        }
16146
16147        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16148            if (origin.staged) {
16149                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
16150                codeFile = origin.file;
16151                resourceFile = origin.file;
16152                return PackageManager.INSTALL_SUCCEEDED;
16153            }
16154
16155            try {
16156                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16157                final File tempDir =
16158                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
16159                codeFile = tempDir;
16160                resourceFile = tempDir;
16161            } catch (IOException e) {
16162                Slog.w(TAG, "Failed to create copy file: " + e);
16163                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
16164            }
16165
16166            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
16167                @Override
16168                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
16169                    if (!FileUtils.isValidExtFilename(name)) {
16170                        throw new IllegalArgumentException("Invalid filename: " + name);
16171                    }
16172                    try {
16173                        final File file = new File(codeFile, name);
16174                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
16175                                O_RDWR | O_CREAT, 0644);
16176                        Os.chmod(file.getAbsolutePath(), 0644);
16177                        return new ParcelFileDescriptor(fd);
16178                    } catch (ErrnoException e) {
16179                        throw new RemoteException("Failed to open: " + e.getMessage());
16180                    }
16181                }
16182            };
16183
16184            int ret = PackageManager.INSTALL_SUCCEEDED;
16185            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
16186            if (ret != PackageManager.INSTALL_SUCCEEDED) {
16187                Slog.e(TAG, "Failed to copy package");
16188                return ret;
16189            }
16190
16191            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
16192            NativeLibraryHelper.Handle handle = null;
16193            try {
16194                handle = NativeLibraryHelper.Handle.create(codeFile);
16195                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
16196                        abiOverride);
16197            } catch (IOException e) {
16198                Slog.e(TAG, "Copying native libraries failed", e);
16199                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16200            } finally {
16201                IoUtils.closeQuietly(handle);
16202            }
16203
16204            return ret;
16205        }
16206
16207        int doPreInstall(int status) {
16208            if (status != PackageManager.INSTALL_SUCCEEDED) {
16209                cleanUp();
16210            }
16211            return status;
16212        }
16213
16214        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16215            if (status != PackageManager.INSTALL_SUCCEEDED) {
16216                cleanUp();
16217                return false;
16218            }
16219
16220            final File targetDir = codeFile.getParentFile();
16221            final File beforeCodeFile = codeFile;
16222            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
16223
16224            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
16225            try {
16226                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
16227            } catch (ErrnoException e) {
16228                Slog.w(TAG, "Failed to rename", e);
16229                return false;
16230            }
16231
16232            if (!SELinux.restoreconRecursive(afterCodeFile)) {
16233                Slog.w(TAG, "Failed to restorecon");
16234                return false;
16235            }
16236
16237            // Reflect the rename internally
16238            codeFile = afterCodeFile;
16239            resourceFile = afterCodeFile;
16240
16241            // Reflect the rename in scanned details
16242            pkg.setCodePath(afterCodeFile.getAbsolutePath());
16243            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16244                    afterCodeFile, pkg.baseCodePath));
16245            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16246                    afterCodeFile, pkg.splitCodePaths));
16247
16248            // Reflect the rename in app info
16249            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16250            pkg.setApplicationInfoCodePath(pkg.codePath);
16251            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16252            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16253            pkg.setApplicationInfoResourcePath(pkg.codePath);
16254            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16255            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16256
16257            return true;
16258        }
16259
16260        int doPostInstall(int status, int uid) {
16261            if (status != PackageManager.INSTALL_SUCCEEDED) {
16262                cleanUp();
16263            }
16264            return status;
16265        }
16266
16267        @Override
16268        String getCodePath() {
16269            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16270        }
16271
16272        @Override
16273        String getResourcePath() {
16274            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16275        }
16276
16277        private boolean cleanUp() {
16278            if (codeFile == null || !codeFile.exists()) {
16279                return false;
16280            }
16281
16282            removeCodePathLI(codeFile);
16283
16284            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
16285                resourceFile.delete();
16286            }
16287
16288            return true;
16289        }
16290
16291        void cleanUpResourcesLI() {
16292            // Try enumerating all code paths before deleting
16293            List<String> allCodePaths = Collections.EMPTY_LIST;
16294            if (codeFile != null && codeFile.exists()) {
16295                try {
16296                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16297                    allCodePaths = pkg.getAllCodePaths();
16298                } catch (PackageParserException e) {
16299                    // Ignored; we tried our best
16300                }
16301            }
16302
16303            cleanUp();
16304            removeDexFiles(allCodePaths, instructionSets);
16305        }
16306
16307        boolean doPostDeleteLI(boolean delete) {
16308            // XXX err, shouldn't we respect the delete flag?
16309            cleanUpResourcesLI();
16310            return true;
16311        }
16312    }
16313
16314    private boolean isAsecExternal(String cid) {
16315        final String asecPath = PackageHelper.getSdFilesystem(cid);
16316        return !asecPath.startsWith(mAsecInternalPath);
16317    }
16318
16319    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
16320            PackageManagerException {
16321        if (copyRet < 0) {
16322            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
16323                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
16324                throw new PackageManagerException(copyRet, message);
16325            }
16326        }
16327    }
16328
16329    /**
16330     * Extract the StorageManagerService "container ID" from the full code path of an
16331     * .apk.
16332     */
16333    static String cidFromCodePath(String fullCodePath) {
16334        int eidx = fullCodePath.lastIndexOf("/");
16335        String subStr1 = fullCodePath.substring(0, eidx);
16336        int sidx = subStr1.lastIndexOf("/");
16337        return subStr1.substring(sidx+1, eidx);
16338    }
16339
16340    /**
16341     * Logic to handle installation of ASEC applications, including copying and
16342     * renaming logic.
16343     */
16344    class AsecInstallArgs extends InstallArgs {
16345        static final String RES_FILE_NAME = "pkg.apk";
16346        static final String PUBLIC_RES_FILE_NAME = "res.zip";
16347
16348        String cid;
16349        String packagePath;
16350        String resourcePath;
16351
16352        /** New install */
16353        AsecInstallArgs(InstallParams params) {
16354            super(params.origin, params.move, params.observer, params.installFlags,
16355                    params.installerPackageName, params.volumeUuid,
16356                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
16357                    params.grantedRuntimePermissions,
16358                    params.traceMethod, params.traceCookie, params.certificates,
16359                    params.installReason);
16360        }
16361
16362        /** Existing install */
16363        AsecInstallArgs(String fullCodePath, String[] instructionSets,
16364                        boolean isExternal, boolean isForwardLocked) {
16365            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
16366                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
16367                    instructionSets, null, null, null, 0, null /*certificates*/,
16368                    PackageManager.INSTALL_REASON_UNKNOWN);
16369            // Hackily pretend we're still looking at a full code path
16370            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
16371                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
16372            }
16373
16374            // Extract cid from fullCodePath
16375            int eidx = fullCodePath.lastIndexOf("/");
16376            String subStr1 = fullCodePath.substring(0, eidx);
16377            int sidx = subStr1.lastIndexOf("/");
16378            cid = subStr1.substring(sidx+1, eidx);
16379            setMountPath(subStr1);
16380        }
16381
16382        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
16383            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
16384                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
16385                    instructionSets, null, null, null, 0, null /*certificates*/,
16386                    PackageManager.INSTALL_REASON_UNKNOWN);
16387            this.cid = cid;
16388            setMountPath(PackageHelper.getSdDir(cid));
16389        }
16390
16391        void createCopyFile() {
16392            cid = mInstallerService.allocateExternalStageCidLegacy();
16393        }
16394
16395        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16396            if (origin.staged && origin.cid != null) {
16397                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
16398                cid = origin.cid;
16399                setMountPath(PackageHelper.getSdDir(cid));
16400                return PackageManager.INSTALL_SUCCEEDED;
16401            }
16402
16403            if (temp) {
16404                createCopyFile();
16405            } else {
16406                /*
16407                 * Pre-emptively destroy the container since it's destroyed if
16408                 * copying fails due to it existing anyway.
16409                 */
16410                PackageHelper.destroySdDir(cid);
16411            }
16412
16413            final String newMountPath = imcs.copyPackageToContainer(
16414                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
16415                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
16416
16417            if (newMountPath != null) {
16418                setMountPath(newMountPath);
16419                return PackageManager.INSTALL_SUCCEEDED;
16420            } else {
16421                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16422            }
16423        }
16424
16425        @Override
16426        String getCodePath() {
16427            return packagePath;
16428        }
16429
16430        @Override
16431        String getResourcePath() {
16432            return resourcePath;
16433        }
16434
16435        int doPreInstall(int status) {
16436            if (status != PackageManager.INSTALL_SUCCEEDED) {
16437                // Destroy container
16438                PackageHelper.destroySdDir(cid);
16439            } else {
16440                boolean mounted = PackageHelper.isContainerMounted(cid);
16441                if (!mounted) {
16442                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
16443                            Process.SYSTEM_UID);
16444                    if (newMountPath != null) {
16445                        setMountPath(newMountPath);
16446                    } else {
16447                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16448                    }
16449                }
16450            }
16451            return status;
16452        }
16453
16454        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16455            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
16456            String newMountPath = null;
16457            if (PackageHelper.isContainerMounted(cid)) {
16458                // Unmount the container
16459                if (!PackageHelper.unMountSdDir(cid)) {
16460                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
16461                    return false;
16462                }
16463            }
16464            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
16465                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
16466                        " which might be stale. Will try to clean up.");
16467                // Clean up the stale container and proceed to recreate.
16468                if (!PackageHelper.destroySdDir(newCacheId)) {
16469                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
16470                    return false;
16471                }
16472                // Successfully cleaned up stale container. Try to rename again.
16473                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
16474                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
16475                            + " inspite of cleaning it up.");
16476                    return false;
16477                }
16478            }
16479            if (!PackageHelper.isContainerMounted(newCacheId)) {
16480                Slog.w(TAG, "Mounting container " + newCacheId);
16481                newMountPath = PackageHelper.mountSdDir(newCacheId,
16482                        getEncryptKey(), Process.SYSTEM_UID);
16483            } else {
16484                newMountPath = PackageHelper.getSdDir(newCacheId);
16485            }
16486            if (newMountPath == null) {
16487                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
16488                return false;
16489            }
16490            Log.i(TAG, "Succesfully renamed " + cid +
16491                    " to " + newCacheId +
16492                    " at new path: " + newMountPath);
16493            cid = newCacheId;
16494
16495            final File beforeCodeFile = new File(packagePath);
16496            setMountPath(newMountPath);
16497            final File afterCodeFile = new File(packagePath);
16498
16499            // Reflect the rename in scanned details
16500            pkg.setCodePath(afterCodeFile.getAbsolutePath());
16501            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16502                    afterCodeFile, pkg.baseCodePath));
16503            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16504                    afterCodeFile, pkg.splitCodePaths));
16505
16506            // Reflect the rename in app info
16507            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16508            pkg.setApplicationInfoCodePath(pkg.codePath);
16509            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16510            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16511            pkg.setApplicationInfoResourcePath(pkg.codePath);
16512            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16513            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16514
16515            return true;
16516        }
16517
16518        private void setMountPath(String mountPath) {
16519            final File mountFile = new File(mountPath);
16520
16521            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
16522            if (monolithicFile.exists()) {
16523                packagePath = monolithicFile.getAbsolutePath();
16524                if (isFwdLocked()) {
16525                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
16526                } else {
16527                    resourcePath = packagePath;
16528                }
16529            } else {
16530                packagePath = mountFile.getAbsolutePath();
16531                resourcePath = packagePath;
16532            }
16533        }
16534
16535        int doPostInstall(int status, int uid) {
16536            if (status != PackageManager.INSTALL_SUCCEEDED) {
16537                cleanUp();
16538            } else {
16539                final int groupOwner;
16540                final String protectedFile;
16541                if (isFwdLocked()) {
16542                    groupOwner = UserHandle.getSharedAppGid(uid);
16543                    protectedFile = RES_FILE_NAME;
16544                } else {
16545                    groupOwner = -1;
16546                    protectedFile = null;
16547                }
16548
16549                if (uid < Process.FIRST_APPLICATION_UID
16550                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
16551                    Slog.e(TAG, "Failed to finalize " + cid);
16552                    PackageHelper.destroySdDir(cid);
16553                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16554                }
16555
16556                boolean mounted = PackageHelper.isContainerMounted(cid);
16557                if (!mounted) {
16558                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
16559                }
16560            }
16561            return status;
16562        }
16563
16564        private void cleanUp() {
16565            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
16566
16567            // Destroy secure container
16568            PackageHelper.destroySdDir(cid);
16569        }
16570
16571        private List<String> getAllCodePaths() {
16572            final File codeFile = new File(getCodePath());
16573            if (codeFile != null && codeFile.exists()) {
16574                try {
16575                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16576                    return pkg.getAllCodePaths();
16577                } catch (PackageParserException e) {
16578                    // Ignored; we tried our best
16579                }
16580            }
16581            return Collections.EMPTY_LIST;
16582        }
16583
16584        void cleanUpResourcesLI() {
16585            // Enumerate all code paths before deleting
16586            cleanUpResourcesLI(getAllCodePaths());
16587        }
16588
16589        private void cleanUpResourcesLI(List<String> allCodePaths) {
16590            cleanUp();
16591            removeDexFiles(allCodePaths, instructionSets);
16592        }
16593
16594        String getPackageName() {
16595            return getAsecPackageName(cid);
16596        }
16597
16598        boolean doPostDeleteLI(boolean delete) {
16599            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
16600            final List<String> allCodePaths = getAllCodePaths();
16601            boolean mounted = PackageHelper.isContainerMounted(cid);
16602            if (mounted) {
16603                // Unmount first
16604                if (PackageHelper.unMountSdDir(cid)) {
16605                    mounted = false;
16606                }
16607            }
16608            if (!mounted && delete) {
16609                cleanUpResourcesLI(allCodePaths);
16610            }
16611            return !mounted;
16612        }
16613
16614        @Override
16615        int doPreCopy() {
16616            if (isFwdLocked()) {
16617                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
16618                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
16619                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16620                }
16621            }
16622
16623            return PackageManager.INSTALL_SUCCEEDED;
16624        }
16625
16626        @Override
16627        int doPostCopy(int uid) {
16628            if (isFwdLocked()) {
16629                if (uid < Process.FIRST_APPLICATION_UID
16630                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
16631                                RES_FILE_NAME)) {
16632                    Slog.e(TAG, "Failed to finalize " + cid);
16633                    PackageHelper.destroySdDir(cid);
16634                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16635                }
16636            }
16637
16638            return PackageManager.INSTALL_SUCCEEDED;
16639        }
16640    }
16641
16642    /**
16643     * Logic to handle movement of existing installed applications.
16644     */
16645    class MoveInstallArgs extends InstallArgs {
16646        private File codeFile;
16647        private File resourceFile;
16648
16649        /** New install */
16650        MoveInstallArgs(InstallParams params) {
16651            super(params.origin, params.move, params.observer, params.installFlags,
16652                    params.installerPackageName, params.volumeUuid,
16653                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
16654                    params.grantedRuntimePermissions,
16655                    params.traceMethod, params.traceCookie, params.certificates,
16656                    params.installReason);
16657        }
16658
16659        int copyApk(IMediaContainerService imcs, boolean temp) {
16660            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
16661                    + move.fromUuid + " to " + move.toUuid);
16662            synchronized (mInstaller) {
16663                try {
16664                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
16665                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
16666                } catch (InstallerException e) {
16667                    Slog.w(TAG, "Failed to move app", e);
16668                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16669                }
16670            }
16671
16672            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
16673            resourceFile = codeFile;
16674            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
16675
16676            return PackageManager.INSTALL_SUCCEEDED;
16677        }
16678
16679        int doPreInstall(int status) {
16680            if (status != PackageManager.INSTALL_SUCCEEDED) {
16681                cleanUp(move.toUuid);
16682            }
16683            return status;
16684        }
16685
16686        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16687            if (status != PackageManager.INSTALL_SUCCEEDED) {
16688                cleanUp(move.toUuid);
16689                return false;
16690            }
16691
16692            // Reflect the move in app info
16693            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16694            pkg.setApplicationInfoCodePath(pkg.codePath);
16695            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16696            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16697            pkg.setApplicationInfoResourcePath(pkg.codePath);
16698            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16699            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16700
16701            return true;
16702        }
16703
16704        int doPostInstall(int status, int uid) {
16705            if (status == PackageManager.INSTALL_SUCCEEDED) {
16706                cleanUp(move.fromUuid);
16707            } else {
16708                cleanUp(move.toUuid);
16709            }
16710            return status;
16711        }
16712
16713        @Override
16714        String getCodePath() {
16715            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16716        }
16717
16718        @Override
16719        String getResourcePath() {
16720            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16721        }
16722
16723        private boolean cleanUp(String volumeUuid) {
16724            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
16725                    move.dataAppName);
16726            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
16727            final int[] userIds = sUserManager.getUserIds();
16728            synchronized (mInstallLock) {
16729                // Clean up both app data and code
16730                // All package moves are frozen until finished
16731                for (int userId : userIds) {
16732                    try {
16733                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
16734                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
16735                    } catch (InstallerException e) {
16736                        Slog.w(TAG, String.valueOf(e));
16737                    }
16738                }
16739                removeCodePathLI(codeFile);
16740            }
16741            return true;
16742        }
16743
16744        void cleanUpResourcesLI() {
16745            throw new UnsupportedOperationException();
16746        }
16747
16748        boolean doPostDeleteLI(boolean delete) {
16749            throw new UnsupportedOperationException();
16750        }
16751    }
16752
16753    static String getAsecPackageName(String packageCid) {
16754        int idx = packageCid.lastIndexOf("-");
16755        if (idx == -1) {
16756            return packageCid;
16757        }
16758        return packageCid.substring(0, idx);
16759    }
16760
16761    // Utility method used to create code paths based on package name and available index.
16762    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
16763        String idxStr = "";
16764        int idx = 1;
16765        // Fall back to default value of idx=1 if prefix is not
16766        // part of oldCodePath
16767        if (oldCodePath != null) {
16768            String subStr = oldCodePath;
16769            // Drop the suffix right away
16770            if (suffix != null && subStr.endsWith(suffix)) {
16771                subStr = subStr.substring(0, subStr.length() - suffix.length());
16772            }
16773            // If oldCodePath already contains prefix find out the
16774            // ending index to either increment or decrement.
16775            int sidx = subStr.lastIndexOf(prefix);
16776            if (sidx != -1) {
16777                subStr = subStr.substring(sidx + prefix.length());
16778                if (subStr != null) {
16779                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
16780                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
16781                    }
16782                    try {
16783                        idx = Integer.parseInt(subStr);
16784                        if (idx <= 1) {
16785                            idx++;
16786                        } else {
16787                            idx--;
16788                        }
16789                    } catch(NumberFormatException e) {
16790                    }
16791                }
16792            }
16793        }
16794        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
16795        return prefix + idxStr;
16796    }
16797
16798    private File getNextCodePath(File targetDir, String packageName) {
16799        File result;
16800        SecureRandom random = new SecureRandom();
16801        byte[] bytes = new byte[16];
16802        do {
16803            random.nextBytes(bytes);
16804            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
16805            result = new File(targetDir, packageName + "-" + suffix);
16806        } while (result.exists());
16807        return result;
16808    }
16809
16810    // Utility method that returns the relative package path with respect
16811    // to the installation directory. Like say for /data/data/com.test-1.apk
16812    // string com.test-1 is returned.
16813    static String deriveCodePathName(String codePath) {
16814        if (codePath == null) {
16815            return null;
16816        }
16817        final File codeFile = new File(codePath);
16818        final String name = codeFile.getName();
16819        if (codeFile.isDirectory()) {
16820            return name;
16821        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
16822            final int lastDot = name.lastIndexOf('.');
16823            return name.substring(0, lastDot);
16824        } else {
16825            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
16826            return null;
16827        }
16828    }
16829
16830    static class PackageInstalledInfo {
16831        String name;
16832        int uid;
16833        // The set of users that originally had this package installed.
16834        int[] origUsers;
16835        // The set of users that now have this package installed.
16836        int[] newUsers;
16837        PackageParser.Package pkg;
16838        int returnCode;
16839        String returnMsg;
16840        PackageRemovedInfo removedInfo;
16841        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
16842
16843        public void setError(int code, String msg) {
16844            setReturnCode(code);
16845            setReturnMessage(msg);
16846            Slog.w(TAG, msg);
16847        }
16848
16849        public void setError(String msg, PackageParserException e) {
16850            setReturnCode(e.error);
16851            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16852            Slog.w(TAG, msg, e);
16853        }
16854
16855        public void setError(String msg, PackageManagerException e) {
16856            returnCode = e.error;
16857            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16858            Slog.w(TAG, msg, e);
16859        }
16860
16861        public void setReturnCode(int returnCode) {
16862            this.returnCode = returnCode;
16863            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16864            for (int i = 0; i < childCount; i++) {
16865                addedChildPackages.valueAt(i).returnCode = returnCode;
16866            }
16867        }
16868
16869        private void setReturnMessage(String returnMsg) {
16870            this.returnMsg = returnMsg;
16871            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16872            for (int i = 0; i < childCount; i++) {
16873                addedChildPackages.valueAt(i).returnMsg = returnMsg;
16874            }
16875        }
16876
16877        // In some error cases we want to convey more info back to the observer
16878        String origPackage;
16879        String origPermission;
16880    }
16881
16882    /*
16883     * Install a non-existing package.
16884     */
16885    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
16886            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
16887            PackageInstalledInfo res, int installReason) {
16888        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
16889
16890        // Remember this for later, in case we need to rollback this install
16891        String pkgName = pkg.packageName;
16892
16893        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
16894
16895        synchronized(mPackages) {
16896            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
16897            if (renamedPackage != null) {
16898                // A package with the same name is already installed, though
16899                // it has been renamed to an older name.  The package we
16900                // are trying to install should be installed as an update to
16901                // the existing one, but that has not been requested, so bail.
16902                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
16903                        + " without first uninstalling package running as "
16904                        + renamedPackage);
16905                return;
16906            }
16907            if (mPackages.containsKey(pkgName)) {
16908                // Don't allow installation over an existing package with the same name.
16909                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
16910                        + " without first uninstalling.");
16911                return;
16912            }
16913        }
16914
16915        try {
16916            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
16917                    System.currentTimeMillis(), user);
16918
16919            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
16920
16921            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16922                prepareAppDataAfterInstallLIF(newPackage);
16923
16924            } else {
16925                // Remove package from internal structures, but keep around any
16926                // data that might have already existed
16927                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
16928                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
16929            }
16930        } catch (PackageManagerException e) {
16931            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16932        }
16933
16934        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16935    }
16936
16937    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
16938        // Can't rotate keys during boot or if sharedUser.
16939        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
16940                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
16941            return false;
16942        }
16943        // app is using upgradeKeySets; make sure all are valid
16944        KeySetManagerService ksms = mSettings.mKeySetManagerService;
16945        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
16946        for (int i = 0; i < upgradeKeySets.length; i++) {
16947            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
16948                Slog.wtf(TAG, "Package "
16949                         + (oldPs.name != null ? oldPs.name : "<null>")
16950                         + " contains upgrade-key-set reference to unknown key-set: "
16951                         + upgradeKeySets[i]
16952                         + " reverting to signatures check.");
16953                return false;
16954            }
16955        }
16956        return true;
16957    }
16958
16959    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
16960        // Upgrade keysets are being used.  Determine if new package has a superset of the
16961        // required keys.
16962        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
16963        KeySetManagerService ksms = mSettings.mKeySetManagerService;
16964        for (int i = 0; i < upgradeKeySets.length; i++) {
16965            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
16966            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
16967                return true;
16968            }
16969        }
16970        return false;
16971    }
16972
16973    private static void updateDigest(MessageDigest digest, File file) throws IOException {
16974        try (DigestInputStream digestStream =
16975                new DigestInputStream(new FileInputStream(file), digest)) {
16976            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
16977        }
16978    }
16979
16980    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
16981            UserHandle user, String installerPackageName, PackageInstalledInfo res,
16982            int installReason) {
16983        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16984
16985        final PackageParser.Package oldPackage;
16986        final PackageSetting ps;
16987        final String pkgName = pkg.packageName;
16988        final int[] allUsers;
16989        final int[] installedUsers;
16990
16991        synchronized(mPackages) {
16992            oldPackage = mPackages.get(pkgName);
16993            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
16994
16995            // don't allow upgrade to target a release SDK from a pre-release SDK
16996            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
16997                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
16998            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
16999                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17000            if (oldTargetsPreRelease
17001                    && !newTargetsPreRelease
17002                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
17003                Slog.w(TAG, "Can't install package targeting released sdk");
17004                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
17005                return;
17006            }
17007
17008            ps = mSettings.mPackages.get(pkgName);
17009
17010            // verify signatures are valid
17011            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
17012                if (!checkUpgradeKeySetLP(ps, pkg)) {
17013                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17014                            "New package not signed by keys specified by upgrade-keysets: "
17015                                    + pkgName);
17016                    return;
17017                }
17018            } else {
17019                // default to original signature matching
17020                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
17021                        != PackageManager.SIGNATURE_MATCH) {
17022                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17023                            "New package has a different signature: " + pkgName);
17024                    return;
17025                }
17026            }
17027
17028            // don't allow a system upgrade unless the upgrade hash matches
17029            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
17030                byte[] digestBytes = null;
17031                try {
17032                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
17033                    updateDigest(digest, new File(pkg.baseCodePath));
17034                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
17035                        for (String path : pkg.splitCodePaths) {
17036                            updateDigest(digest, new File(path));
17037                        }
17038                    }
17039                    digestBytes = digest.digest();
17040                } catch (NoSuchAlgorithmException | IOException e) {
17041                    res.setError(INSTALL_FAILED_INVALID_APK,
17042                            "Could not compute hash: " + pkgName);
17043                    return;
17044                }
17045                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
17046                    res.setError(INSTALL_FAILED_INVALID_APK,
17047                            "New package fails restrict-update check: " + pkgName);
17048                    return;
17049                }
17050                // retain upgrade restriction
17051                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
17052            }
17053
17054            // Check for shared user id changes
17055            String invalidPackageName =
17056                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
17057            if (invalidPackageName != null) {
17058                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
17059                        "Package " + invalidPackageName + " tried to change user "
17060                                + oldPackage.mSharedUserId);
17061                return;
17062            }
17063
17064            // In case of rollback, remember per-user/profile install state
17065            allUsers = sUserManager.getUserIds();
17066            installedUsers = ps.queryInstalledUsers(allUsers, true);
17067
17068            // don't allow an upgrade from full to ephemeral
17069            if (isInstantApp) {
17070                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
17071                    for (int currentUser : allUsers) {
17072                        if (!ps.getInstantApp(currentUser)) {
17073                            // can't downgrade from full to instant
17074                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17075                                    + " for user: " + currentUser);
17076                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17077                            return;
17078                        }
17079                    }
17080                } else if (!ps.getInstantApp(user.getIdentifier())) {
17081                    // can't downgrade from full to instant
17082                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17083                            + " for user: " + user.getIdentifier());
17084                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17085                    return;
17086                }
17087            }
17088        }
17089
17090        // Update what is removed
17091        res.removedInfo = new PackageRemovedInfo(this);
17092        res.removedInfo.uid = oldPackage.applicationInfo.uid;
17093        res.removedInfo.removedPackage = oldPackage.packageName;
17094        res.removedInfo.installerPackageName = ps.installerPackageName;
17095        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
17096        res.removedInfo.isUpdate = true;
17097        res.removedInfo.origUsers = installedUsers;
17098        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
17099        for (int i = 0; i < installedUsers.length; i++) {
17100            final int userId = installedUsers[i];
17101            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
17102        }
17103
17104        final int childCount = (oldPackage.childPackages != null)
17105                ? oldPackage.childPackages.size() : 0;
17106        for (int i = 0; i < childCount; i++) {
17107            boolean childPackageUpdated = false;
17108            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
17109            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17110            if (res.addedChildPackages != null) {
17111                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17112                if (childRes != null) {
17113                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
17114                    childRes.removedInfo.removedPackage = childPkg.packageName;
17115                    if (childPs != null) {
17116                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17117                    }
17118                    childRes.removedInfo.isUpdate = true;
17119                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
17120                    childPackageUpdated = true;
17121                }
17122            }
17123            if (!childPackageUpdated) {
17124                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
17125                childRemovedRes.removedPackage = childPkg.packageName;
17126                if (childPs != null) {
17127                    childRemovedRes.installerPackageName = childPs.installerPackageName;
17128                }
17129                childRemovedRes.isUpdate = false;
17130                childRemovedRes.dataRemoved = true;
17131                synchronized (mPackages) {
17132                    if (childPs != null) {
17133                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
17134                    }
17135                }
17136                if (res.removedInfo.removedChildPackages == null) {
17137                    res.removedInfo.removedChildPackages = new ArrayMap<>();
17138                }
17139                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
17140            }
17141        }
17142
17143        boolean sysPkg = (isSystemApp(oldPackage));
17144        if (sysPkg) {
17145            // Set the system/privileged flags as needed
17146            final boolean privileged =
17147                    (oldPackage.applicationInfo.privateFlags
17148                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17149            final int systemPolicyFlags = policyFlags
17150                    | PackageParser.PARSE_IS_SYSTEM
17151                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
17152
17153            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
17154                    user, allUsers, installerPackageName, res, installReason);
17155        } else {
17156            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
17157                    user, allUsers, installerPackageName, res, installReason);
17158        }
17159    }
17160
17161    @Override
17162    public List<String> getPreviousCodePaths(String packageName) {
17163        final int callingUid = Binder.getCallingUid();
17164        final List<String> result = new ArrayList<>();
17165        if (getInstantAppPackageName(callingUid) != null) {
17166            return result;
17167        }
17168        final PackageSetting ps = mSettings.mPackages.get(packageName);
17169        if (ps != null
17170                && ps.oldCodePaths != null
17171                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
17172            result.addAll(ps.oldCodePaths);
17173        }
17174        return result;
17175    }
17176
17177    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
17178            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17179            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17180            int installReason) {
17181        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
17182                + deletedPackage);
17183
17184        String pkgName = deletedPackage.packageName;
17185        boolean deletedPkg = true;
17186        boolean addedPkg = false;
17187        boolean updatedSettings = false;
17188        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
17189        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
17190                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
17191
17192        final long origUpdateTime = (pkg.mExtras != null)
17193                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
17194
17195        // First delete the existing package while retaining the data directory
17196        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17197                res.removedInfo, true, pkg)) {
17198            // If the existing package wasn't successfully deleted
17199            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
17200            deletedPkg = false;
17201        } else {
17202            // Successfully deleted the old package; proceed with replace.
17203
17204            // If deleted package lived in a container, give users a chance to
17205            // relinquish resources before killing.
17206            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
17207                if (DEBUG_INSTALL) {
17208                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
17209                }
17210                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
17211                final ArrayList<String> pkgList = new ArrayList<String>(1);
17212                pkgList.add(deletedPackage.applicationInfo.packageName);
17213                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
17214            }
17215
17216            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17217                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17218            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17219
17220            try {
17221                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
17222                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
17223                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17224                        installReason);
17225
17226                // Update the in-memory copy of the previous code paths.
17227                PackageSetting ps = mSettings.mPackages.get(pkgName);
17228                if (!killApp) {
17229                    if (ps.oldCodePaths == null) {
17230                        ps.oldCodePaths = new ArraySet<>();
17231                    }
17232                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
17233                    if (deletedPackage.splitCodePaths != null) {
17234                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
17235                    }
17236                } else {
17237                    ps.oldCodePaths = null;
17238                }
17239                if (ps.childPackageNames != null) {
17240                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
17241                        final String childPkgName = ps.childPackageNames.get(i);
17242                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
17243                        childPs.oldCodePaths = ps.oldCodePaths;
17244                    }
17245                }
17246                // set instant app status, but, only if it's explicitly specified
17247                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17248                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
17249                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
17250                prepareAppDataAfterInstallLIF(newPackage);
17251                addedPkg = true;
17252                mDexManager.notifyPackageUpdated(newPackage.packageName,
17253                        newPackage.baseCodePath, newPackage.splitCodePaths);
17254            } catch (PackageManagerException e) {
17255                res.setError("Package couldn't be installed in " + pkg.codePath, e);
17256            }
17257        }
17258
17259        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17260            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
17261
17262            // Revert all internal state mutations and added folders for the failed install
17263            if (addedPkg) {
17264                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17265                        res.removedInfo, true, null);
17266            }
17267
17268            // Restore the old package
17269            if (deletedPkg) {
17270                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
17271                File restoreFile = new File(deletedPackage.codePath);
17272                // Parse old package
17273                boolean oldExternal = isExternal(deletedPackage);
17274                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
17275                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
17276                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
17277                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
17278                try {
17279                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
17280                            null);
17281                } catch (PackageManagerException e) {
17282                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
17283                            + e.getMessage());
17284                    return;
17285                }
17286
17287                synchronized (mPackages) {
17288                    // Ensure the installer package name up to date
17289                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17290
17291                    // Update permissions for restored package
17292                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17293
17294                    mSettings.writeLPr();
17295                }
17296
17297                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
17298            }
17299        } else {
17300            synchronized (mPackages) {
17301                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
17302                if (ps != null) {
17303                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
17304                    if (res.removedInfo.removedChildPackages != null) {
17305                        final int childCount = res.removedInfo.removedChildPackages.size();
17306                        // Iterate in reverse as we may modify the collection
17307                        for (int i = childCount - 1; i >= 0; i--) {
17308                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
17309                            if (res.addedChildPackages.containsKey(childPackageName)) {
17310                                res.removedInfo.removedChildPackages.removeAt(i);
17311                            } else {
17312                                PackageRemovedInfo childInfo = res.removedInfo
17313                                        .removedChildPackages.valueAt(i);
17314                                childInfo.removedForAllUsers = mPackages.get(
17315                                        childInfo.removedPackage) == null;
17316                            }
17317                        }
17318                    }
17319                }
17320            }
17321        }
17322    }
17323
17324    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
17325            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17326            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17327            int installReason) {
17328        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
17329                + ", old=" + deletedPackage);
17330
17331        final boolean disabledSystem;
17332
17333        // Remove existing system package
17334        removePackageLI(deletedPackage, true);
17335
17336        synchronized (mPackages) {
17337            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
17338        }
17339        if (!disabledSystem) {
17340            // We didn't need to disable the .apk as a current system package,
17341            // which means we are replacing another update that is already
17342            // installed.  We need to make sure to delete the older one's .apk.
17343            res.removedInfo.args = createInstallArgsForExisting(0,
17344                    deletedPackage.applicationInfo.getCodePath(),
17345                    deletedPackage.applicationInfo.getResourcePath(),
17346                    getAppDexInstructionSets(deletedPackage.applicationInfo));
17347        } else {
17348            res.removedInfo.args = null;
17349        }
17350
17351        // Successfully disabled the old package. Now proceed with re-installation
17352        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17353                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17354        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17355
17356        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17357        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
17358                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
17359
17360        PackageParser.Package newPackage = null;
17361        try {
17362            // Add the package to the internal data structures
17363            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
17364
17365            // Set the update and install times
17366            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
17367            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
17368                    System.currentTimeMillis());
17369
17370            // Update the package dynamic state if succeeded
17371            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17372                // Now that the install succeeded make sure we remove data
17373                // directories for any child package the update removed.
17374                final int deletedChildCount = (deletedPackage.childPackages != null)
17375                        ? deletedPackage.childPackages.size() : 0;
17376                final int newChildCount = (newPackage.childPackages != null)
17377                        ? newPackage.childPackages.size() : 0;
17378                for (int i = 0; i < deletedChildCount; i++) {
17379                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
17380                    boolean childPackageDeleted = true;
17381                    for (int j = 0; j < newChildCount; j++) {
17382                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
17383                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
17384                            childPackageDeleted = false;
17385                            break;
17386                        }
17387                    }
17388                    if (childPackageDeleted) {
17389                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
17390                                deletedChildPkg.packageName);
17391                        if (ps != null && res.removedInfo.removedChildPackages != null) {
17392                            PackageRemovedInfo removedChildRes = res.removedInfo
17393                                    .removedChildPackages.get(deletedChildPkg.packageName);
17394                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
17395                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
17396                        }
17397                    }
17398                }
17399
17400                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17401                        installReason);
17402                prepareAppDataAfterInstallLIF(newPackage);
17403
17404                mDexManager.notifyPackageUpdated(newPackage.packageName,
17405                            newPackage.baseCodePath, newPackage.splitCodePaths);
17406            }
17407        } catch (PackageManagerException e) {
17408            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
17409            res.setError("Package couldn't be installed in " + pkg.codePath, e);
17410        }
17411
17412        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17413            // Re installation failed. Restore old information
17414            // Remove new pkg information
17415            if (newPackage != null) {
17416                removeInstalledPackageLI(newPackage, true);
17417            }
17418            // Add back the old system package
17419            try {
17420                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
17421            } catch (PackageManagerException e) {
17422                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
17423            }
17424
17425            synchronized (mPackages) {
17426                if (disabledSystem) {
17427                    enableSystemPackageLPw(deletedPackage);
17428                }
17429
17430                // Ensure the installer package name up to date
17431                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17432
17433                // Update permissions for restored package
17434                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17435
17436                mSettings.writeLPr();
17437            }
17438
17439            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
17440                    + " after failed upgrade");
17441        }
17442    }
17443
17444    /**
17445     * Checks whether the parent or any of the child packages have a change shared
17446     * user. For a package to be a valid update the shred users of the parent and
17447     * the children should match. We may later support changing child shared users.
17448     * @param oldPkg The updated package.
17449     * @param newPkg The update package.
17450     * @return The shared user that change between the versions.
17451     */
17452    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
17453            PackageParser.Package newPkg) {
17454        // Check parent shared user
17455        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
17456            return newPkg.packageName;
17457        }
17458        // Check child shared users
17459        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
17460        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
17461        for (int i = 0; i < newChildCount; i++) {
17462            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
17463            // If this child was present, did it have the same shared user?
17464            for (int j = 0; j < oldChildCount; j++) {
17465                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
17466                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
17467                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
17468                    return newChildPkg.packageName;
17469                }
17470            }
17471        }
17472        return null;
17473    }
17474
17475    private void removeNativeBinariesLI(PackageSetting ps) {
17476        // Remove the lib path for the parent package
17477        if (ps != null) {
17478            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
17479            // Remove the lib path for the child packages
17480            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
17481            for (int i = 0; i < childCount; i++) {
17482                PackageSetting childPs = null;
17483                synchronized (mPackages) {
17484                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
17485                }
17486                if (childPs != null) {
17487                    NativeLibraryHelper.removeNativeBinariesLI(childPs
17488                            .legacyNativeLibraryPathString);
17489                }
17490            }
17491        }
17492    }
17493
17494    private void enableSystemPackageLPw(PackageParser.Package pkg) {
17495        // Enable the parent package
17496        mSettings.enableSystemPackageLPw(pkg.packageName);
17497        // Enable the child packages
17498        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17499        for (int i = 0; i < childCount; i++) {
17500            PackageParser.Package childPkg = pkg.childPackages.get(i);
17501            mSettings.enableSystemPackageLPw(childPkg.packageName);
17502        }
17503    }
17504
17505    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
17506            PackageParser.Package newPkg) {
17507        // Disable the parent package (parent always replaced)
17508        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
17509        // Disable the child packages
17510        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
17511        for (int i = 0; i < childCount; i++) {
17512            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
17513            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
17514            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
17515        }
17516        return disabled;
17517    }
17518
17519    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
17520            String installerPackageName) {
17521        // Enable the parent package
17522        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
17523        // Enable the child packages
17524        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17525        for (int i = 0; i < childCount; i++) {
17526            PackageParser.Package childPkg = pkg.childPackages.get(i);
17527            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
17528        }
17529    }
17530
17531    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
17532        // Collect all used permissions in the UID
17533        ArraySet<String> usedPermissions = new ArraySet<>();
17534        final int packageCount = su.packages.size();
17535        for (int i = 0; i < packageCount; i++) {
17536            PackageSetting ps = su.packages.valueAt(i);
17537            if (ps.pkg == null) {
17538                continue;
17539            }
17540            final int requestedPermCount = ps.pkg.requestedPermissions.size();
17541            for (int j = 0; j < requestedPermCount; j++) {
17542                String permission = ps.pkg.requestedPermissions.get(j);
17543                BasePermission bp = mSettings.mPermissions.get(permission);
17544                if (bp != null) {
17545                    usedPermissions.add(permission);
17546                }
17547            }
17548        }
17549
17550        PermissionsState permissionsState = su.getPermissionsState();
17551        // Prune install permissions
17552        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
17553        final int installPermCount = installPermStates.size();
17554        for (int i = installPermCount - 1; i >= 0;  i--) {
17555            PermissionState permissionState = installPermStates.get(i);
17556            if (!usedPermissions.contains(permissionState.getName())) {
17557                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
17558                if (bp != null) {
17559                    permissionsState.revokeInstallPermission(bp);
17560                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
17561                            PackageManager.MASK_PERMISSION_FLAGS, 0);
17562                }
17563            }
17564        }
17565
17566        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
17567
17568        // Prune runtime permissions
17569        for (int userId : allUserIds) {
17570            List<PermissionState> runtimePermStates = permissionsState
17571                    .getRuntimePermissionStates(userId);
17572            final int runtimePermCount = runtimePermStates.size();
17573            for (int i = runtimePermCount - 1; i >= 0; i--) {
17574                PermissionState permissionState = runtimePermStates.get(i);
17575                if (!usedPermissions.contains(permissionState.getName())) {
17576                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
17577                    if (bp != null) {
17578                        permissionsState.revokeRuntimePermission(bp, userId);
17579                        permissionsState.updatePermissionFlags(bp, userId,
17580                                PackageManager.MASK_PERMISSION_FLAGS, 0);
17581                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
17582                                runtimePermissionChangedUserIds, userId);
17583                    }
17584                }
17585            }
17586        }
17587
17588        return runtimePermissionChangedUserIds;
17589    }
17590
17591    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
17592            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
17593        // Update the parent package setting
17594        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
17595                res, user, installReason);
17596        // Update the child packages setting
17597        final int childCount = (newPackage.childPackages != null)
17598                ? newPackage.childPackages.size() : 0;
17599        for (int i = 0; i < childCount; i++) {
17600            PackageParser.Package childPackage = newPackage.childPackages.get(i);
17601            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
17602            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
17603                    childRes.origUsers, childRes, user, installReason);
17604        }
17605    }
17606
17607    private void updateSettingsInternalLI(PackageParser.Package newPackage,
17608            String installerPackageName, int[] allUsers, int[] installedForUsers,
17609            PackageInstalledInfo res, UserHandle user, int installReason) {
17610        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
17611
17612        String pkgName = newPackage.packageName;
17613        synchronized (mPackages) {
17614            //write settings. the installStatus will be incomplete at this stage.
17615            //note that the new package setting would have already been
17616            //added to mPackages. It hasn't been persisted yet.
17617            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
17618            // TODO: Remove this write? It's also written at the end of this method
17619            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
17620            mSettings.writeLPr();
17621            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17622        }
17623
17624        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
17625        synchronized (mPackages) {
17626            updatePermissionsLPw(newPackage.packageName, newPackage,
17627                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
17628                            ? UPDATE_PERMISSIONS_ALL : 0));
17629            // For system-bundled packages, we assume that installing an upgraded version
17630            // of the package implies that the user actually wants to run that new code,
17631            // so we enable the package.
17632            PackageSetting ps = mSettings.mPackages.get(pkgName);
17633            final int userId = user.getIdentifier();
17634            if (ps != null) {
17635                if (isSystemApp(newPackage)) {
17636                    if (DEBUG_INSTALL) {
17637                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
17638                    }
17639                    // Enable system package for requested users
17640                    if (res.origUsers != null) {
17641                        for (int origUserId : res.origUsers) {
17642                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
17643                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
17644                                        origUserId, installerPackageName);
17645                            }
17646                        }
17647                    }
17648                    // Also convey the prior install/uninstall state
17649                    if (allUsers != null && installedForUsers != null) {
17650                        for (int currentUserId : allUsers) {
17651                            final boolean installed = ArrayUtils.contains(
17652                                    installedForUsers, currentUserId);
17653                            if (DEBUG_INSTALL) {
17654                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
17655                            }
17656                            ps.setInstalled(installed, currentUserId);
17657                        }
17658                        // these install state changes will be persisted in the
17659                        // upcoming call to mSettings.writeLPr().
17660                    }
17661                }
17662                // It's implied that when a user requests installation, they want the app to be
17663                // installed and enabled.
17664                if (userId != UserHandle.USER_ALL) {
17665                    ps.setInstalled(true, userId);
17666                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
17667                }
17668
17669                // When replacing an existing package, preserve the original install reason for all
17670                // users that had the package installed before.
17671                final Set<Integer> previousUserIds = new ArraySet<>();
17672                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
17673                    final int installReasonCount = res.removedInfo.installReasons.size();
17674                    for (int i = 0; i < installReasonCount; i++) {
17675                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
17676                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
17677                        ps.setInstallReason(previousInstallReason, previousUserId);
17678                        previousUserIds.add(previousUserId);
17679                    }
17680                }
17681
17682                // Set install reason for users that are having the package newly installed.
17683                if (userId == UserHandle.USER_ALL) {
17684                    for (int currentUserId : sUserManager.getUserIds()) {
17685                        if (!previousUserIds.contains(currentUserId)) {
17686                            ps.setInstallReason(installReason, currentUserId);
17687                        }
17688                    }
17689                } else if (!previousUserIds.contains(userId)) {
17690                    ps.setInstallReason(installReason, userId);
17691                }
17692                mSettings.writeKernelMappingLPr(ps);
17693            }
17694            res.name = pkgName;
17695            res.uid = newPackage.applicationInfo.uid;
17696            res.pkg = newPackage;
17697            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
17698            mSettings.setInstallerPackageName(pkgName, installerPackageName);
17699            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17700            //to update install status
17701            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
17702            mSettings.writeLPr();
17703            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17704        }
17705
17706        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17707    }
17708
17709    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
17710        try {
17711            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
17712            installPackageLI(args, res);
17713        } finally {
17714            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17715        }
17716    }
17717
17718    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
17719        final int installFlags = args.installFlags;
17720        final String installerPackageName = args.installerPackageName;
17721        final String volumeUuid = args.volumeUuid;
17722        final File tmpPackageFile = new File(args.getCodePath());
17723        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
17724        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
17725                || (args.volumeUuid != null));
17726        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
17727        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
17728        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
17729        boolean replace = false;
17730        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
17731        if (args.move != null) {
17732            // moving a complete application; perform an initial scan on the new install location
17733            scanFlags |= SCAN_INITIAL;
17734        }
17735        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
17736            scanFlags |= SCAN_DONT_KILL_APP;
17737        }
17738        if (instantApp) {
17739            scanFlags |= SCAN_AS_INSTANT_APP;
17740        }
17741        if (fullApp) {
17742            scanFlags |= SCAN_AS_FULL_APP;
17743        }
17744
17745        // Result object to be returned
17746        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17747
17748        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
17749
17750        // Sanity check
17751        if (instantApp && (forwardLocked || onExternal)) {
17752            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
17753                    + " external=" + onExternal);
17754            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17755            return;
17756        }
17757
17758        // Retrieve PackageSettings and parse package
17759        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
17760                | PackageParser.PARSE_ENFORCE_CODE
17761                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
17762                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
17763                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
17764                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
17765        PackageParser pp = new PackageParser();
17766        pp.setSeparateProcesses(mSeparateProcesses);
17767        pp.setDisplayMetrics(mMetrics);
17768        pp.setCallback(mPackageParserCallback);
17769
17770        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
17771        final PackageParser.Package pkg;
17772        try {
17773            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
17774        } catch (PackageParserException e) {
17775            res.setError("Failed parse during installPackageLI", e);
17776            return;
17777        } finally {
17778            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17779        }
17780
17781        // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
17782        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
17783            Slog.w(TAG, "Instant app package " + pkg.packageName
17784                    + " does not target O, this will be a fatal error.");
17785            // STOPSHIP: Make this a fatal error
17786            pkg.applicationInfo.targetSdkVersion = Build.VERSION_CODES.O;
17787        }
17788        if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
17789            Slog.w(TAG, "Instant app package " + pkg.packageName
17790                    + " does not target targetSandboxVersion 2, this will be a fatal error.");
17791            // STOPSHIP: Make this a fatal error
17792            pkg.applicationInfo.targetSandboxVersion = 2;
17793        }
17794
17795        if (pkg.applicationInfo.isStaticSharedLibrary()) {
17796            // Static shared libraries have synthetic package names
17797            renameStaticSharedLibraryPackage(pkg);
17798
17799            // No static shared libs on external storage
17800            if (onExternal) {
17801                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
17802                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17803                        "Packages declaring static-shared libs cannot be updated");
17804                return;
17805            }
17806        }
17807
17808        // If we are installing a clustered package add results for the children
17809        if (pkg.childPackages != null) {
17810            synchronized (mPackages) {
17811                final int childCount = pkg.childPackages.size();
17812                for (int i = 0; i < childCount; i++) {
17813                    PackageParser.Package childPkg = pkg.childPackages.get(i);
17814                    PackageInstalledInfo childRes = new PackageInstalledInfo();
17815                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17816                    childRes.pkg = childPkg;
17817                    childRes.name = childPkg.packageName;
17818                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17819                    if (childPs != null) {
17820                        childRes.origUsers = childPs.queryInstalledUsers(
17821                                sUserManager.getUserIds(), true);
17822                    }
17823                    if ((mPackages.containsKey(childPkg.packageName))) {
17824                        childRes.removedInfo = new PackageRemovedInfo(this);
17825                        childRes.removedInfo.removedPackage = childPkg.packageName;
17826                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17827                    }
17828                    if (res.addedChildPackages == null) {
17829                        res.addedChildPackages = new ArrayMap<>();
17830                    }
17831                    res.addedChildPackages.put(childPkg.packageName, childRes);
17832                }
17833            }
17834        }
17835
17836        // If package doesn't declare API override, mark that we have an install
17837        // time CPU ABI override.
17838        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
17839            pkg.cpuAbiOverride = args.abiOverride;
17840        }
17841
17842        String pkgName = res.name = pkg.packageName;
17843        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
17844            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
17845                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
17846                return;
17847            }
17848        }
17849
17850        try {
17851            // either use what we've been given or parse directly from the APK
17852            if (args.certificates != null) {
17853                try {
17854                    PackageParser.populateCertificates(pkg, args.certificates);
17855                } catch (PackageParserException e) {
17856                    // there was something wrong with the certificates we were given;
17857                    // try to pull them from the APK
17858                    PackageParser.collectCertificates(pkg, parseFlags);
17859                }
17860            } else {
17861                PackageParser.collectCertificates(pkg, parseFlags);
17862            }
17863        } catch (PackageParserException e) {
17864            res.setError("Failed collect during installPackageLI", e);
17865            return;
17866        }
17867
17868        // Get rid of all references to package scan path via parser.
17869        pp = null;
17870        String oldCodePath = null;
17871        boolean systemApp = false;
17872        synchronized (mPackages) {
17873            // Check if installing already existing package
17874            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
17875                String oldName = mSettings.getRenamedPackageLPr(pkgName);
17876                if (pkg.mOriginalPackages != null
17877                        && pkg.mOriginalPackages.contains(oldName)
17878                        && mPackages.containsKey(oldName)) {
17879                    // This package is derived from an original package,
17880                    // and this device has been updating from that original
17881                    // name.  We must continue using the original name, so
17882                    // rename the new package here.
17883                    pkg.setPackageName(oldName);
17884                    pkgName = pkg.packageName;
17885                    replace = true;
17886                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
17887                            + oldName + " pkgName=" + pkgName);
17888                } else if (mPackages.containsKey(pkgName)) {
17889                    // This package, under its official name, already exists
17890                    // on the device; we should replace it.
17891                    replace = true;
17892                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
17893                }
17894
17895                // Child packages are installed through the parent package
17896                if (pkg.parentPackage != null) {
17897                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
17898                            "Package " + pkg.packageName + " is child of package "
17899                                    + pkg.parentPackage.parentPackage + ". Child packages "
17900                                    + "can be updated only through the parent package.");
17901                    return;
17902                }
17903
17904                if (replace) {
17905                    // Prevent apps opting out from runtime permissions
17906                    PackageParser.Package oldPackage = mPackages.get(pkgName);
17907                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
17908                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
17909                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
17910                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
17911                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
17912                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
17913                                        + " doesn't support runtime permissions but the old"
17914                                        + " target SDK " + oldTargetSdk + " does.");
17915                        return;
17916                    }
17917                    // Prevent apps from downgrading their targetSandbox.
17918                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
17919                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
17920                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
17921                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17922                                "Package " + pkg.packageName + " new target sandbox "
17923                                + newTargetSandbox + " is incompatible with the previous value of"
17924                                + oldTargetSandbox + ".");
17925                        return;
17926                    }
17927
17928                    // Prevent installing of child packages
17929                    if (oldPackage.parentPackage != null) {
17930                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
17931                                "Package " + pkg.packageName + " is child of package "
17932                                        + oldPackage.parentPackage + ". Child packages "
17933                                        + "can be updated only through the parent package.");
17934                        return;
17935                    }
17936                }
17937            }
17938
17939            PackageSetting ps = mSettings.mPackages.get(pkgName);
17940            if (ps != null) {
17941                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
17942
17943                // Static shared libs have same package with different versions where
17944                // we internally use a synthetic package name to allow multiple versions
17945                // of the same package, therefore we need to compare signatures against
17946                // the package setting for the latest library version.
17947                PackageSetting signatureCheckPs = ps;
17948                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17949                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
17950                    if (libraryEntry != null) {
17951                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
17952                    }
17953                }
17954
17955                // Quick sanity check that we're signed correctly if updating;
17956                // we'll check this again later when scanning, but we want to
17957                // bail early here before tripping over redefined permissions.
17958                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
17959                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
17960                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
17961                                + pkg.packageName + " upgrade keys do not match the "
17962                                + "previously installed version");
17963                        return;
17964                    }
17965                } else {
17966                    try {
17967                        verifySignaturesLP(signatureCheckPs, pkg);
17968                    } catch (PackageManagerException e) {
17969                        res.setError(e.error, e.getMessage());
17970                        return;
17971                    }
17972                }
17973
17974                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
17975                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
17976                    systemApp = (ps.pkg.applicationInfo.flags &
17977                            ApplicationInfo.FLAG_SYSTEM) != 0;
17978                }
17979                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17980            }
17981
17982            int N = pkg.permissions.size();
17983            for (int i = N-1; i >= 0; i--) {
17984                PackageParser.Permission perm = pkg.permissions.get(i);
17985                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
17986
17987                // Don't allow anyone but the system to define ephemeral permissions.
17988                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_EPHEMERAL) != 0
17989                        && !systemApp) {
17990                    Slog.w(TAG, "Non-System package " + pkg.packageName
17991                            + " attempting to delcare ephemeral permission "
17992                            + perm.info.name + "; Removing ephemeral.");
17993                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_EPHEMERAL;
17994                }
17995                // Check whether the newly-scanned package wants to define an already-defined perm
17996                if (bp != null) {
17997                    // If the defining package is signed with our cert, it's okay.  This
17998                    // also includes the "updating the same package" case, of course.
17999                    // "updating same package" could also involve key-rotation.
18000                    final boolean sigsOk;
18001                    if (bp.sourcePackage.equals(pkg.packageName)
18002                            && (bp.packageSetting instanceof PackageSetting)
18003                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
18004                                    scanFlags))) {
18005                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
18006                    } else {
18007                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
18008                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
18009                    }
18010                    if (!sigsOk) {
18011                        // If the owning package is the system itself, we log but allow
18012                        // install to proceed; we fail the install on all other permission
18013                        // redefinitions.
18014                        if (!bp.sourcePackage.equals("android")) {
18015                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
18016                                    + pkg.packageName + " attempting to redeclare permission "
18017                                    + perm.info.name + " already owned by " + bp.sourcePackage);
18018                            res.origPermission = perm.info.name;
18019                            res.origPackage = bp.sourcePackage;
18020                            return;
18021                        } else {
18022                            Slog.w(TAG, "Package " + pkg.packageName
18023                                    + " attempting to redeclare system permission "
18024                                    + perm.info.name + "; ignoring new declaration");
18025                            pkg.permissions.remove(i);
18026                        }
18027                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
18028                        // Prevent apps to change protection level to dangerous from any other
18029                        // type as this would allow a privilege escalation where an app adds a
18030                        // normal/signature permission in other app's group and later redefines
18031                        // it as dangerous leading to the group auto-grant.
18032                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
18033                                == PermissionInfo.PROTECTION_DANGEROUS) {
18034                            if (bp != null && !bp.isRuntime()) {
18035                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
18036                                        + "non-runtime permission " + perm.info.name
18037                                        + " to runtime; keeping old protection level");
18038                                perm.info.protectionLevel = bp.protectionLevel;
18039                            }
18040                        }
18041                    }
18042                }
18043            }
18044        }
18045
18046        if (systemApp) {
18047            if (onExternal) {
18048                // Abort update; system app can't be replaced with app on sdcard
18049                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
18050                        "Cannot install updates to system apps on sdcard");
18051                return;
18052            } else if (instantApp) {
18053                // Abort update; system app can't be replaced with an instant app
18054                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
18055                        "Cannot update a system app with an instant app");
18056                return;
18057            }
18058        }
18059
18060        if (args.move != null) {
18061            // We did an in-place move, so dex is ready to roll
18062            scanFlags |= SCAN_NO_DEX;
18063            scanFlags |= SCAN_MOVE;
18064
18065            synchronized (mPackages) {
18066                final PackageSetting ps = mSettings.mPackages.get(pkgName);
18067                if (ps == null) {
18068                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
18069                            "Missing settings for moved package " + pkgName);
18070                }
18071
18072                // We moved the entire application as-is, so bring over the
18073                // previously derived ABI information.
18074                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
18075                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
18076            }
18077
18078        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
18079            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
18080            scanFlags |= SCAN_NO_DEX;
18081
18082            try {
18083                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
18084                    args.abiOverride : pkg.cpuAbiOverride);
18085                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
18086                        true /*extractLibs*/, mAppLib32InstallDir);
18087            } catch (PackageManagerException pme) {
18088                Slog.e(TAG, "Error deriving application ABI", pme);
18089                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
18090                return;
18091            }
18092
18093            // Shared libraries for the package need to be updated.
18094            synchronized (mPackages) {
18095                try {
18096                    updateSharedLibrariesLPr(pkg, null);
18097                } catch (PackageManagerException e) {
18098                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18099                }
18100            }
18101
18102            // dexopt can take some time to complete, so, for instant apps, we skip this
18103            // step during installation. Instead, we'll take extra time the first time the
18104            // instant app starts. It's preferred to do it this way to provide continuous
18105            // progress to the user instead of mysteriously blocking somewhere in the
18106            // middle of running an instant app.
18107            if (!instantApp) {
18108                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
18109                // Do not run PackageDexOptimizer through the local performDexOpt
18110                // method because `pkg` may not be in `mPackages` yet.
18111                //
18112                // Also, don't fail application installs if the dexopt step fails.
18113                mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
18114                        null /* instructionSets */, false /* checkProfiles */,
18115                        getCompilerFilterForReason(REASON_INSTALL),
18116                        getOrCreateCompilerPackageStats(pkg),
18117                        mDexManager.isUsedByOtherApps(pkg.packageName));
18118                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18119            }
18120
18121            // Notify BackgroundDexOptService that the package has been changed.
18122            // If this is an update of a package which used to fail to compile,
18123            // BDOS will remove it from its blacklist.
18124            // TODO: Layering violation
18125            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
18126        }
18127
18128        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
18129            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
18130            return;
18131        }
18132
18133        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
18134
18135        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
18136                "installPackageLI")) {
18137            if (replace) {
18138                if (pkg.applicationInfo.isStaticSharedLibrary()) {
18139                    // Static libs have a synthetic package name containing the version
18140                    // and cannot be updated as an update would get a new package name,
18141                    // unless this is the exact same version code which is useful for
18142                    // development.
18143                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
18144                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
18145                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
18146                                + "static-shared libs cannot be updated");
18147                        return;
18148                    }
18149                }
18150                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
18151                        installerPackageName, res, args.installReason);
18152            } else {
18153                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
18154                        args.user, installerPackageName, volumeUuid, res, args.installReason);
18155            }
18156        }
18157
18158        synchronized (mPackages) {
18159            final PackageSetting ps = mSettings.mPackages.get(pkgName);
18160            if (ps != null) {
18161                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18162                ps.setUpdateAvailable(false /*updateAvailable*/);
18163            }
18164
18165            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18166            for (int i = 0; i < childCount; i++) {
18167                PackageParser.Package childPkg = pkg.childPackages.get(i);
18168                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
18169                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
18170                if (childPs != null) {
18171                    childRes.newUsers = childPs.queryInstalledUsers(
18172                            sUserManager.getUserIds(), true);
18173                }
18174            }
18175
18176            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
18177                updateSequenceNumberLP(ps, res.newUsers);
18178                updateInstantAppInstallerLocked(pkgName);
18179            }
18180        }
18181    }
18182
18183    private void startIntentFilterVerifications(int userId, boolean replacing,
18184            PackageParser.Package pkg) {
18185        if (mIntentFilterVerifierComponent == null) {
18186            Slog.w(TAG, "No IntentFilter verification will not be done as "
18187                    + "there is no IntentFilterVerifier available!");
18188            return;
18189        }
18190
18191        final int verifierUid = getPackageUid(
18192                mIntentFilterVerifierComponent.getPackageName(),
18193                MATCH_DEBUG_TRIAGED_MISSING,
18194                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
18195
18196        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18197        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
18198        mHandler.sendMessage(msg);
18199
18200        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18201        for (int i = 0; i < childCount; i++) {
18202            PackageParser.Package childPkg = pkg.childPackages.get(i);
18203            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18204            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
18205            mHandler.sendMessage(msg);
18206        }
18207    }
18208
18209    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
18210            PackageParser.Package pkg) {
18211        int size = pkg.activities.size();
18212        if (size == 0) {
18213            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18214                    "No activity, so no need to verify any IntentFilter!");
18215            return;
18216        }
18217
18218        final boolean hasDomainURLs = hasDomainURLs(pkg);
18219        if (!hasDomainURLs) {
18220            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18221                    "No domain URLs, so no need to verify any IntentFilter!");
18222            return;
18223        }
18224
18225        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
18226                + " if any IntentFilter from the " + size
18227                + " Activities needs verification ...");
18228
18229        int count = 0;
18230        final String packageName = pkg.packageName;
18231
18232        synchronized (mPackages) {
18233            // If this is a new install and we see that we've already run verification for this
18234            // package, we have nothing to do: it means the state was restored from backup.
18235            if (!replacing) {
18236                IntentFilterVerificationInfo ivi =
18237                        mSettings.getIntentFilterVerificationLPr(packageName);
18238                if (ivi != null) {
18239                    if (DEBUG_DOMAIN_VERIFICATION) {
18240                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
18241                                + ivi.getStatusString());
18242                    }
18243                    return;
18244                }
18245            }
18246
18247            // If any filters need to be verified, then all need to be.
18248            boolean needToVerify = false;
18249            for (PackageParser.Activity a : pkg.activities) {
18250                for (ActivityIntentInfo filter : a.intents) {
18251                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
18252                        if (DEBUG_DOMAIN_VERIFICATION) {
18253                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
18254                        }
18255                        needToVerify = true;
18256                        break;
18257                    }
18258                }
18259            }
18260
18261            if (needToVerify) {
18262                final int verificationId = mIntentFilterVerificationToken++;
18263                for (PackageParser.Activity a : pkg.activities) {
18264                    for (ActivityIntentInfo filter : a.intents) {
18265                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
18266                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18267                                    "Verification needed for IntentFilter:" + filter.toString());
18268                            mIntentFilterVerifier.addOneIntentFilterVerification(
18269                                    verifierUid, userId, verificationId, filter, packageName);
18270                            count++;
18271                        }
18272                    }
18273                }
18274            }
18275        }
18276
18277        if (count > 0) {
18278            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
18279                    + " IntentFilter verification" + (count > 1 ? "s" : "")
18280                    +  " for userId:" + userId);
18281            mIntentFilterVerifier.startVerifications(userId);
18282        } else {
18283            if (DEBUG_DOMAIN_VERIFICATION) {
18284                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
18285            }
18286        }
18287    }
18288
18289    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
18290        final ComponentName cn  = filter.activity.getComponentName();
18291        final String packageName = cn.getPackageName();
18292
18293        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
18294                packageName);
18295        if (ivi == null) {
18296            return true;
18297        }
18298        int status = ivi.getStatus();
18299        switch (status) {
18300            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
18301            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
18302                return true;
18303
18304            default:
18305                // Nothing to do
18306                return false;
18307        }
18308    }
18309
18310    private static boolean isMultiArch(ApplicationInfo info) {
18311        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
18312    }
18313
18314    private static boolean isExternal(PackageParser.Package pkg) {
18315        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18316    }
18317
18318    private static boolean isExternal(PackageSetting ps) {
18319        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18320    }
18321
18322    private static boolean isSystemApp(PackageParser.Package pkg) {
18323        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
18324    }
18325
18326    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
18327        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
18328    }
18329
18330    private static boolean hasDomainURLs(PackageParser.Package pkg) {
18331        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
18332    }
18333
18334    private static boolean isSystemApp(PackageSetting ps) {
18335        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
18336    }
18337
18338    private static boolean isUpdatedSystemApp(PackageSetting ps) {
18339        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
18340    }
18341
18342    private int packageFlagsToInstallFlags(PackageSetting ps) {
18343        int installFlags = 0;
18344        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
18345            // This existing package was an external ASEC install when we have
18346            // the external flag without a UUID
18347            installFlags |= PackageManager.INSTALL_EXTERNAL;
18348        }
18349        if (ps.isForwardLocked()) {
18350            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
18351        }
18352        return installFlags;
18353    }
18354
18355    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
18356        if (isExternal(pkg)) {
18357            if (TextUtils.isEmpty(pkg.volumeUuid)) {
18358                return StorageManager.UUID_PRIMARY_PHYSICAL;
18359            } else {
18360                return pkg.volumeUuid;
18361            }
18362        } else {
18363            return StorageManager.UUID_PRIVATE_INTERNAL;
18364        }
18365    }
18366
18367    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
18368        if (isExternal(pkg)) {
18369            if (TextUtils.isEmpty(pkg.volumeUuid)) {
18370                return mSettings.getExternalVersion();
18371            } else {
18372                return mSettings.findOrCreateVersion(pkg.volumeUuid);
18373            }
18374        } else {
18375            return mSettings.getInternalVersion();
18376        }
18377    }
18378
18379    private void deleteTempPackageFiles() {
18380        final FilenameFilter filter = new FilenameFilter() {
18381            public boolean accept(File dir, String name) {
18382                return name.startsWith("vmdl") && name.endsWith(".tmp");
18383            }
18384        };
18385        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
18386            file.delete();
18387        }
18388    }
18389
18390    @Override
18391    public void deletePackageAsUser(String packageName, int versionCode,
18392            IPackageDeleteObserver observer, int userId, int flags) {
18393        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
18394                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
18395    }
18396
18397    @Override
18398    public void deletePackageVersioned(VersionedPackage versionedPackage,
18399            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
18400        final int callingUid = Binder.getCallingUid();
18401        mContext.enforceCallingOrSelfPermission(
18402                android.Manifest.permission.DELETE_PACKAGES, null);
18403        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
18404        Preconditions.checkNotNull(versionedPackage);
18405        Preconditions.checkNotNull(observer);
18406        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
18407                PackageManager.VERSION_CODE_HIGHEST,
18408                Integer.MAX_VALUE, "versionCode must be >= -1");
18409
18410        final String packageName = versionedPackage.getPackageName();
18411        final int versionCode = versionedPackage.getVersionCode();
18412        final String internalPackageName;
18413        synchronized (mPackages) {
18414            // Normalize package name to handle renamed packages and static libs
18415            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
18416                    versionedPackage.getVersionCode());
18417        }
18418
18419        final int uid = Binder.getCallingUid();
18420        if (!isOrphaned(internalPackageName)
18421                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
18422            try {
18423                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
18424                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
18425                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
18426                observer.onUserActionRequired(intent);
18427            } catch (RemoteException re) {
18428            }
18429            return;
18430        }
18431        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
18432        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
18433        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
18434            mContext.enforceCallingOrSelfPermission(
18435                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
18436                    "deletePackage for user " + userId);
18437        }
18438
18439        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
18440            try {
18441                observer.onPackageDeleted(packageName,
18442                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
18443            } catch (RemoteException re) {
18444            }
18445            return;
18446        }
18447
18448        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
18449            try {
18450                observer.onPackageDeleted(packageName,
18451                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
18452            } catch (RemoteException re) {
18453            }
18454            return;
18455        }
18456
18457        if (DEBUG_REMOVE) {
18458            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
18459                    + " deleteAllUsers: " + deleteAllUsers + " version="
18460                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
18461                    ? "VERSION_CODE_HIGHEST" : versionCode));
18462        }
18463        // Queue up an async operation since the package deletion may take a little while.
18464        mHandler.post(new Runnable() {
18465            public void run() {
18466                mHandler.removeCallbacks(this);
18467                int returnCode;
18468                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
18469                boolean doDeletePackage = true;
18470                if (ps != null) {
18471                    final boolean targetIsInstantApp =
18472                            ps.getInstantApp(UserHandle.getUserId(callingUid));
18473                    doDeletePackage = !targetIsInstantApp
18474                            || canViewInstantApps;
18475                }
18476                if (doDeletePackage) {
18477                    if (!deleteAllUsers) {
18478                        returnCode = deletePackageX(internalPackageName, versionCode,
18479                                userId, deleteFlags);
18480                    } else {
18481                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
18482                                internalPackageName, users);
18483                        // If nobody is blocking uninstall, proceed with delete for all users
18484                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
18485                            returnCode = deletePackageX(internalPackageName, versionCode,
18486                                    userId, deleteFlags);
18487                        } else {
18488                            // Otherwise uninstall individually for users with blockUninstalls=false
18489                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
18490                            for (int userId : users) {
18491                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
18492                                    returnCode = deletePackageX(internalPackageName, versionCode,
18493                                            userId, userFlags);
18494                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
18495                                        Slog.w(TAG, "Package delete failed for user " + userId
18496                                                + ", returnCode " + returnCode);
18497                                    }
18498                                }
18499                            }
18500                            // The app has only been marked uninstalled for certain users.
18501                            // We still need to report that delete was blocked
18502                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
18503                        }
18504                    }
18505                } else {
18506                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18507                }
18508                try {
18509                    observer.onPackageDeleted(packageName, returnCode, null);
18510                } catch (RemoteException e) {
18511                    Log.i(TAG, "Observer no longer exists.");
18512                } //end catch
18513            } //end run
18514        });
18515    }
18516
18517    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
18518        if (pkg.staticSharedLibName != null) {
18519            return pkg.manifestPackageName;
18520        }
18521        return pkg.packageName;
18522    }
18523
18524    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
18525        // Handle renamed packages
18526        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
18527        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
18528
18529        // Is this a static library?
18530        SparseArray<SharedLibraryEntry> versionedLib =
18531                mStaticLibsByDeclaringPackage.get(packageName);
18532        if (versionedLib == null || versionedLib.size() <= 0) {
18533            return packageName;
18534        }
18535
18536        // Figure out which lib versions the caller can see
18537        SparseIntArray versionsCallerCanSee = null;
18538        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
18539        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
18540                && callingAppId != Process.ROOT_UID) {
18541            versionsCallerCanSee = new SparseIntArray();
18542            String libName = versionedLib.valueAt(0).info.getName();
18543            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
18544            if (uidPackages != null) {
18545                for (String uidPackage : uidPackages) {
18546                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
18547                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
18548                    if (libIdx >= 0) {
18549                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
18550                        versionsCallerCanSee.append(libVersion, libVersion);
18551                    }
18552                }
18553            }
18554        }
18555
18556        // Caller can see nothing - done
18557        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
18558            return packageName;
18559        }
18560
18561        // Find the version the caller can see and the app version code
18562        SharedLibraryEntry highestVersion = null;
18563        final int versionCount = versionedLib.size();
18564        for (int i = 0; i < versionCount; i++) {
18565            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
18566            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
18567                    libEntry.info.getVersion()) < 0) {
18568                continue;
18569            }
18570            final int libVersionCode = libEntry.info.getDeclaringPackage().getVersionCode();
18571            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
18572                if (libVersionCode == versionCode) {
18573                    return libEntry.apk;
18574                }
18575            } else if (highestVersion == null) {
18576                highestVersion = libEntry;
18577            } else if (libVersionCode  > highestVersion.info
18578                    .getDeclaringPackage().getVersionCode()) {
18579                highestVersion = libEntry;
18580            }
18581        }
18582
18583        if (highestVersion != null) {
18584            return highestVersion.apk;
18585        }
18586
18587        return packageName;
18588    }
18589
18590    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
18591        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
18592              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
18593            return true;
18594        }
18595        final int callingUserId = UserHandle.getUserId(callingUid);
18596        // If the caller installed the pkgName, then allow it to silently uninstall.
18597        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
18598            return true;
18599        }
18600
18601        // Allow package verifier to silently uninstall.
18602        if (mRequiredVerifierPackage != null &&
18603                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
18604            return true;
18605        }
18606
18607        // Allow package uninstaller to silently uninstall.
18608        if (mRequiredUninstallerPackage != null &&
18609                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
18610            return true;
18611        }
18612
18613        // Allow storage manager to silently uninstall.
18614        if (mStorageManagerPackage != null &&
18615                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
18616            return true;
18617        }
18618        return false;
18619    }
18620
18621    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
18622        int[] result = EMPTY_INT_ARRAY;
18623        for (int userId : userIds) {
18624            if (getBlockUninstallForUser(packageName, userId)) {
18625                result = ArrayUtils.appendInt(result, userId);
18626            }
18627        }
18628        return result;
18629    }
18630
18631    @Override
18632    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
18633        final int callingUid = Binder.getCallingUid();
18634        if (getInstantAppPackageName(callingUid) != null
18635                && !isCallerSameApp(packageName, callingUid)) {
18636            return false;
18637        }
18638        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
18639    }
18640
18641    private boolean isPackageDeviceAdmin(String packageName, int userId) {
18642        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
18643                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
18644        try {
18645            if (dpm != null) {
18646                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
18647                        /* callingUserOnly =*/ false);
18648                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
18649                        : deviceOwnerComponentName.getPackageName();
18650                // Does the package contains the device owner?
18651                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
18652                // this check is probably not needed, since DO should be registered as a device
18653                // admin on some user too. (Original bug for this: b/17657954)
18654                if (packageName.equals(deviceOwnerPackageName)) {
18655                    return true;
18656                }
18657                // Does it contain a device admin for any user?
18658                int[] users;
18659                if (userId == UserHandle.USER_ALL) {
18660                    users = sUserManager.getUserIds();
18661                } else {
18662                    users = new int[]{userId};
18663                }
18664                for (int i = 0; i < users.length; ++i) {
18665                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
18666                        return true;
18667                    }
18668                }
18669            }
18670        } catch (RemoteException e) {
18671        }
18672        return false;
18673    }
18674
18675    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
18676        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
18677    }
18678
18679    /**
18680     *  This method is an internal method that could be get invoked either
18681     *  to delete an installed package or to clean up a failed installation.
18682     *  After deleting an installed package, a broadcast is sent to notify any
18683     *  listeners that the package has been removed. For cleaning up a failed
18684     *  installation, the broadcast is not necessary since the package's
18685     *  installation wouldn't have sent the initial broadcast either
18686     *  The key steps in deleting a package are
18687     *  deleting the package information in internal structures like mPackages,
18688     *  deleting the packages base directories through installd
18689     *  updating mSettings to reflect current status
18690     *  persisting settings for later use
18691     *  sending a broadcast if necessary
18692     */
18693    int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
18694        final PackageRemovedInfo info = new PackageRemovedInfo(this);
18695        final boolean res;
18696
18697        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
18698                ? UserHandle.USER_ALL : userId;
18699
18700        if (isPackageDeviceAdmin(packageName, removeUser)) {
18701            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
18702            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
18703        }
18704
18705        PackageSetting uninstalledPs = null;
18706        PackageParser.Package pkg = null;
18707
18708        // for the uninstall-updates case and restricted profiles, remember the per-
18709        // user handle installed state
18710        int[] allUsers;
18711        synchronized (mPackages) {
18712            uninstalledPs = mSettings.mPackages.get(packageName);
18713            if (uninstalledPs == null) {
18714                Slog.w(TAG, "Not removing non-existent package " + packageName);
18715                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18716            }
18717
18718            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
18719                    && uninstalledPs.versionCode != versionCode) {
18720                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
18721                        + uninstalledPs.versionCode + " != " + versionCode);
18722                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18723            }
18724
18725            // Static shared libs can be declared by any package, so let us not
18726            // allow removing a package if it provides a lib others depend on.
18727            pkg = mPackages.get(packageName);
18728
18729            allUsers = sUserManager.getUserIds();
18730
18731            if (pkg != null && pkg.staticSharedLibName != null) {
18732                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
18733                        pkg.staticSharedLibVersion);
18734                if (libEntry != null) {
18735                    for (int currUserId : allUsers) {
18736                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
18737                            continue;
18738                        }
18739                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
18740                                libEntry.info, 0, currUserId);
18741                        if (!ArrayUtils.isEmpty(libClientPackages)) {
18742                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
18743                                    + " hosting lib " + libEntry.info.getName() + " version "
18744                                    + libEntry.info.getVersion() + " used by " + libClientPackages
18745                                    + " for user " + currUserId);
18746                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
18747                        }
18748                    }
18749                }
18750            }
18751
18752            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
18753        }
18754
18755        final int freezeUser;
18756        if (isUpdatedSystemApp(uninstalledPs)
18757                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
18758            // We're downgrading a system app, which will apply to all users, so
18759            // freeze them all during the downgrade
18760            freezeUser = UserHandle.USER_ALL;
18761        } else {
18762            freezeUser = removeUser;
18763        }
18764
18765        synchronized (mInstallLock) {
18766            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
18767            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
18768                    deleteFlags, "deletePackageX")) {
18769                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
18770                        deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
18771            }
18772            synchronized (mPackages) {
18773                if (res) {
18774                    if (pkg != null) {
18775                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
18776                    }
18777                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
18778                    updateInstantAppInstallerLocked(packageName);
18779                }
18780            }
18781        }
18782
18783        if (res) {
18784            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
18785            info.sendPackageRemovedBroadcasts(killApp);
18786            info.sendSystemPackageUpdatedBroadcasts();
18787            info.sendSystemPackageAppearedBroadcasts();
18788        }
18789        // Force a gc here.
18790        Runtime.getRuntime().gc();
18791        // Delete the resources here after sending the broadcast to let
18792        // other processes clean up before deleting resources.
18793        if (info.args != null) {
18794            synchronized (mInstallLock) {
18795                info.args.doPostDeleteLI(true);
18796            }
18797        }
18798
18799        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18800    }
18801
18802    static class PackageRemovedInfo {
18803        final PackageSender packageSender;
18804        String removedPackage;
18805        String installerPackageName;
18806        int uid = -1;
18807        int removedAppId = -1;
18808        int[] origUsers;
18809        int[] removedUsers = null;
18810        int[] broadcastUsers = null;
18811        SparseArray<Integer> installReasons;
18812        boolean isRemovedPackageSystemUpdate = false;
18813        boolean isUpdate;
18814        boolean dataRemoved;
18815        boolean removedForAllUsers;
18816        boolean isStaticSharedLib;
18817        // Clean up resources deleted packages.
18818        InstallArgs args = null;
18819        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
18820        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
18821
18822        PackageRemovedInfo(PackageSender packageSender) {
18823            this.packageSender = packageSender;
18824        }
18825
18826        void sendPackageRemovedBroadcasts(boolean killApp) {
18827            sendPackageRemovedBroadcastInternal(killApp);
18828            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
18829            for (int i = 0; i < childCount; i++) {
18830                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18831                childInfo.sendPackageRemovedBroadcastInternal(killApp);
18832            }
18833        }
18834
18835        void sendSystemPackageUpdatedBroadcasts() {
18836            if (isRemovedPackageSystemUpdate) {
18837                sendSystemPackageUpdatedBroadcastsInternal();
18838                final int childCount = (removedChildPackages != null)
18839                        ? removedChildPackages.size() : 0;
18840                for (int i = 0; i < childCount; i++) {
18841                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18842                    if (childInfo.isRemovedPackageSystemUpdate) {
18843                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
18844                    }
18845                }
18846            }
18847        }
18848
18849        void sendSystemPackageAppearedBroadcasts() {
18850            final int packageCount = (appearedChildPackages != null)
18851                    ? appearedChildPackages.size() : 0;
18852            for (int i = 0; i < packageCount; i++) {
18853                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
18854                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
18855                    true, UserHandle.getAppId(installedInfo.uid),
18856                    installedInfo.newUsers);
18857            }
18858        }
18859
18860        private void sendSystemPackageUpdatedBroadcastsInternal() {
18861            Bundle extras = new Bundle(2);
18862            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
18863            extras.putBoolean(Intent.EXTRA_REPLACING, true);
18864            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18865                removedPackage, extras, 0, null /*targetPackage*/, null, null);
18866            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18867                removedPackage, extras, 0, null /*targetPackage*/, null, null);
18868            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
18869                null, null, 0, removedPackage, null, null);
18870            if (installerPackageName != null) {
18871                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18872                        removedPackage, extras, 0 /*flags*/,
18873                        installerPackageName, null, null);
18874                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18875                        removedPackage, extras, 0 /*flags*/,
18876                        installerPackageName, null, null);
18877            }
18878        }
18879
18880        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
18881            // Don't send static shared library removal broadcasts as these
18882            // libs are visible only the the apps that depend on them an one
18883            // cannot remove the library if it has a dependency.
18884            if (isStaticSharedLib) {
18885                return;
18886            }
18887            Bundle extras = new Bundle(2);
18888            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
18889            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
18890            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
18891            if (isUpdate || isRemovedPackageSystemUpdate) {
18892                extras.putBoolean(Intent.EXTRA_REPLACING, true);
18893            }
18894            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
18895            if (removedPackage != null) {
18896                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18897                    removedPackage, extras, 0, null /*targetPackage*/, null, broadcastUsers);
18898                if (installerPackageName != null) {
18899                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18900                            removedPackage, extras, 0 /*flags*/,
18901                            installerPackageName, null, broadcastUsers);
18902                }
18903                if (dataRemoved && !isRemovedPackageSystemUpdate) {
18904                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
18905                        removedPackage, extras,
18906                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18907                        null, null, broadcastUsers);
18908                }
18909            }
18910            if (removedAppId >= 0) {
18911                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras,
18912                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, null, null, broadcastUsers);
18913            }
18914        }
18915
18916        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
18917            removedUsers = userIds;
18918            if (removedUsers == null) {
18919                broadcastUsers = null;
18920                return;
18921            }
18922
18923            broadcastUsers = EMPTY_INT_ARRAY;
18924            for (int i = userIds.length - 1; i >= 0; --i) {
18925                final int userId = userIds[i];
18926                if (deletedPackageSetting.getInstantApp(userId)) {
18927                    continue;
18928                }
18929                broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
18930            }
18931        }
18932    }
18933
18934    /*
18935     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
18936     * flag is not set, the data directory is removed as well.
18937     * make sure this flag is set for partially installed apps. If not its meaningless to
18938     * delete a partially installed application.
18939     */
18940    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
18941            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
18942        String packageName = ps.name;
18943        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
18944        // Retrieve object to delete permissions for shared user later on
18945        final PackageParser.Package deletedPkg;
18946        final PackageSetting deletedPs;
18947        // reader
18948        synchronized (mPackages) {
18949            deletedPkg = mPackages.get(packageName);
18950            deletedPs = mSettings.mPackages.get(packageName);
18951            if (outInfo != null) {
18952                outInfo.removedPackage = packageName;
18953                outInfo.installerPackageName = ps.installerPackageName;
18954                outInfo.isStaticSharedLib = deletedPkg != null
18955                        && deletedPkg.staticSharedLibName != null;
18956                outInfo.populateUsers(deletedPs == null ? null
18957                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
18958            }
18959        }
18960
18961        removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
18962
18963        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
18964            final PackageParser.Package resolvedPkg;
18965            if (deletedPkg != null) {
18966                resolvedPkg = deletedPkg;
18967            } else {
18968                // We don't have a parsed package when it lives on an ejected
18969                // adopted storage device, so fake something together
18970                resolvedPkg = new PackageParser.Package(ps.name);
18971                resolvedPkg.setVolumeUuid(ps.volumeUuid);
18972            }
18973            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
18974                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18975            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
18976            if (outInfo != null) {
18977                outInfo.dataRemoved = true;
18978            }
18979            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
18980        }
18981
18982        int removedAppId = -1;
18983
18984        // writer
18985        synchronized (mPackages) {
18986            boolean installedStateChanged = false;
18987            if (deletedPs != null) {
18988                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
18989                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
18990                    clearDefaultBrowserIfNeeded(packageName);
18991                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
18992                    removedAppId = mSettings.removePackageLPw(packageName);
18993                    if (outInfo != null) {
18994                        outInfo.removedAppId = removedAppId;
18995                    }
18996                    updatePermissionsLPw(deletedPs.name, null, 0);
18997                    if (deletedPs.sharedUser != null) {
18998                        // Remove permissions associated with package. Since runtime
18999                        // permissions are per user we have to kill the removed package
19000                        // or packages running under the shared user of the removed
19001                        // package if revoking the permissions requested only by the removed
19002                        // package is successful and this causes a change in gids.
19003                        for (int userId : UserManagerService.getInstance().getUserIds()) {
19004                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
19005                                    userId);
19006                            if (userIdToKill == UserHandle.USER_ALL
19007                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
19008                                // If gids changed for this user, kill all affected packages.
19009                                mHandler.post(new Runnable() {
19010                                    @Override
19011                                    public void run() {
19012                                        // This has to happen with no lock held.
19013                                        killApplication(deletedPs.name, deletedPs.appId,
19014                                                KILL_APP_REASON_GIDS_CHANGED);
19015                                    }
19016                                });
19017                                break;
19018                            }
19019                        }
19020                    }
19021                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
19022                }
19023                // make sure to preserve per-user disabled state if this removal was just
19024                // a downgrade of a system app to the factory package
19025                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
19026                    if (DEBUG_REMOVE) {
19027                        Slog.d(TAG, "Propagating install state across downgrade");
19028                    }
19029                    for (int userId : allUserHandles) {
19030                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
19031                        if (DEBUG_REMOVE) {
19032                            Slog.d(TAG, "    user " + userId + " => " + installed);
19033                        }
19034                        if (installed != ps.getInstalled(userId)) {
19035                            installedStateChanged = true;
19036                        }
19037                        ps.setInstalled(installed, userId);
19038                    }
19039                }
19040            }
19041            // can downgrade to reader
19042            if (writeSettings) {
19043                // Save settings now
19044                mSettings.writeLPr();
19045            }
19046            if (installedStateChanged) {
19047                mSettings.writeKernelMappingLPr(ps);
19048            }
19049        }
19050        if (removedAppId != -1) {
19051            // A user ID was deleted here. Go through all users and remove it
19052            // from KeyStore.
19053            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
19054        }
19055    }
19056
19057    static boolean locationIsPrivileged(File path) {
19058        try {
19059            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
19060                    .getCanonicalPath();
19061            return path.getCanonicalPath().startsWith(privilegedAppDir);
19062        } catch (IOException e) {
19063            Slog.e(TAG, "Unable to access code path " + path);
19064        }
19065        return false;
19066    }
19067
19068    /*
19069     * Tries to delete system package.
19070     */
19071    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
19072            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
19073            boolean writeSettings) {
19074        if (deletedPs.parentPackageName != null) {
19075            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
19076            return false;
19077        }
19078
19079        final boolean applyUserRestrictions
19080                = (allUserHandles != null) && (outInfo.origUsers != null);
19081        final PackageSetting disabledPs;
19082        // Confirm if the system package has been updated
19083        // An updated system app can be deleted. This will also have to restore
19084        // the system pkg from system partition
19085        // reader
19086        synchronized (mPackages) {
19087            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
19088        }
19089
19090        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
19091                + " disabledPs=" + disabledPs);
19092
19093        if (disabledPs == null) {
19094            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
19095            return false;
19096        } else if (DEBUG_REMOVE) {
19097            Slog.d(TAG, "Deleting system pkg from data partition");
19098        }
19099
19100        if (DEBUG_REMOVE) {
19101            if (applyUserRestrictions) {
19102                Slog.d(TAG, "Remembering install states:");
19103                for (int userId : allUserHandles) {
19104                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
19105                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
19106                }
19107            }
19108        }
19109
19110        // Delete the updated package
19111        outInfo.isRemovedPackageSystemUpdate = true;
19112        if (outInfo.removedChildPackages != null) {
19113            final int childCount = (deletedPs.childPackageNames != null)
19114                    ? deletedPs.childPackageNames.size() : 0;
19115            for (int i = 0; i < childCount; i++) {
19116                String childPackageName = deletedPs.childPackageNames.get(i);
19117                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
19118                        .contains(childPackageName)) {
19119                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19120                            childPackageName);
19121                    if (childInfo != null) {
19122                        childInfo.isRemovedPackageSystemUpdate = true;
19123                    }
19124                }
19125            }
19126        }
19127
19128        if (disabledPs.versionCode < deletedPs.versionCode) {
19129            // Delete data for downgrades
19130            flags &= ~PackageManager.DELETE_KEEP_DATA;
19131        } else {
19132            // Preserve data by setting flag
19133            flags |= PackageManager.DELETE_KEEP_DATA;
19134        }
19135
19136        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
19137                outInfo, writeSettings, disabledPs.pkg);
19138        if (!ret) {
19139            return false;
19140        }
19141
19142        // writer
19143        synchronized (mPackages) {
19144            // Reinstate the old system package
19145            enableSystemPackageLPw(disabledPs.pkg);
19146            // Remove any native libraries from the upgraded package.
19147            removeNativeBinariesLI(deletedPs);
19148        }
19149
19150        // Install the system package
19151        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
19152        int parseFlags = mDefParseFlags
19153                | PackageParser.PARSE_MUST_BE_APK
19154                | PackageParser.PARSE_IS_SYSTEM
19155                | PackageParser.PARSE_IS_SYSTEM_DIR;
19156        if (locationIsPrivileged(disabledPs.codePath)) {
19157            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
19158        }
19159
19160        final PackageParser.Package newPkg;
19161        try {
19162            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */,
19163                0 /* currentTime */, null);
19164        } catch (PackageManagerException e) {
19165            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
19166                    + e.getMessage());
19167            return false;
19168        }
19169
19170        try {
19171            // update shared libraries for the newly re-installed system package
19172            updateSharedLibrariesLPr(newPkg, null);
19173        } catch (PackageManagerException e) {
19174            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
19175        }
19176
19177        prepareAppDataAfterInstallLIF(newPkg);
19178
19179        // writer
19180        synchronized (mPackages) {
19181            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
19182
19183            // Propagate the permissions state as we do not want to drop on the floor
19184            // runtime permissions. The update permissions method below will take
19185            // care of removing obsolete permissions and grant install permissions.
19186            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
19187            updatePermissionsLPw(newPkg.packageName, newPkg,
19188                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
19189
19190            if (applyUserRestrictions) {
19191                boolean installedStateChanged = false;
19192                if (DEBUG_REMOVE) {
19193                    Slog.d(TAG, "Propagating install state across reinstall");
19194                }
19195                for (int userId : allUserHandles) {
19196                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
19197                    if (DEBUG_REMOVE) {
19198                        Slog.d(TAG, "    user " + userId + " => " + installed);
19199                    }
19200                    if (installed != ps.getInstalled(userId)) {
19201                        installedStateChanged = true;
19202                    }
19203                    ps.setInstalled(installed, userId);
19204
19205                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19206                }
19207                // Regardless of writeSettings we need to ensure that this restriction
19208                // state propagation is persisted
19209                mSettings.writeAllUsersPackageRestrictionsLPr();
19210                if (installedStateChanged) {
19211                    mSettings.writeKernelMappingLPr(ps);
19212                }
19213            }
19214            // can downgrade to reader here
19215            if (writeSettings) {
19216                mSettings.writeLPr();
19217            }
19218        }
19219        return true;
19220    }
19221
19222    private boolean deleteInstalledPackageLIF(PackageSetting ps,
19223            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
19224            PackageRemovedInfo outInfo, boolean writeSettings,
19225            PackageParser.Package replacingPackage) {
19226        synchronized (mPackages) {
19227            if (outInfo != null) {
19228                outInfo.uid = ps.appId;
19229            }
19230
19231            if (outInfo != null && outInfo.removedChildPackages != null) {
19232                final int childCount = (ps.childPackageNames != null)
19233                        ? ps.childPackageNames.size() : 0;
19234                for (int i = 0; i < childCount; i++) {
19235                    String childPackageName = ps.childPackageNames.get(i);
19236                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
19237                    if (childPs == null) {
19238                        return false;
19239                    }
19240                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19241                            childPackageName);
19242                    if (childInfo != null) {
19243                        childInfo.uid = childPs.appId;
19244                    }
19245                }
19246            }
19247        }
19248
19249        // Delete package data from internal structures and also remove data if flag is set
19250        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
19251
19252        // Delete the child packages data
19253        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
19254        for (int i = 0; i < childCount; i++) {
19255            PackageSetting childPs;
19256            synchronized (mPackages) {
19257                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
19258            }
19259            if (childPs != null) {
19260                PackageRemovedInfo childOutInfo = (outInfo != null
19261                        && outInfo.removedChildPackages != null)
19262                        ? outInfo.removedChildPackages.get(childPs.name) : null;
19263                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
19264                        && (replacingPackage != null
19265                        && !replacingPackage.hasChildPackage(childPs.name))
19266                        ? flags & ~DELETE_KEEP_DATA : flags;
19267                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
19268                        deleteFlags, writeSettings);
19269            }
19270        }
19271
19272        // Delete application code and resources only for parent packages
19273        if (ps.parentPackageName == null) {
19274            if (deleteCodeAndResources && (outInfo != null)) {
19275                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
19276                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
19277                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
19278            }
19279        }
19280
19281        return true;
19282    }
19283
19284    @Override
19285    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
19286            int userId) {
19287        mContext.enforceCallingOrSelfPermission(
19288                android.Manifest.permission.DELETE_PACKAGES, null);
19289        synchronized (mPackages) {
19290            // Cannot block uninstall of static shared libs as they are
19291            // considered a part of the using app (emulating static linking).
19292            // Also static libs are installed always on internal storage.
19293            PackageParser.Package pkg = mPackages.get(packageName);
19294            if (pkg != null && pkg.staticSharedLibName != null) {
19295                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
19296                        + " providing static shared library: " + pkg.staticSharedLibName);
19297                return false;
19298            }
19299            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
19300            mSettings.writePackageRestrictionsLPr(userId);
19301        }
19302        return true;
19303    }
19304
19305    @Override
19306    public boolean getBlockUninstallForUser(String packageName, int userId) {
19307        synchronized (mPackages) {
19308            final PackageSetting ps = mSettings.mPackages.get(packageName);
19309            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
19310                return true;
19311            }
19312            return mSettings.getBlockUninstallLPr(userId, packageName);
19313        }
19314    }
19315
19316    @Override
19317    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
19318        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
19319        synchronized (mPackages) {
19320            PackageSetting ps = mSettings.mPackages.get(packageName);
19321            if (ps == null) {
19322                Log.w(TAG, "Package doesn't exist: " + packageName);
19323                return false;
19324            }
19325            if (systemUserApp) {
19326                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
19327            } else {
19328                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
19329            }
19330            mSettings.writeLPr();
19331        }
19332        return true;
19333    }
19334
19335    /*
19336     * This method handles package deletion in general
19337     */
19338    private boolean deletePackageLIF(String packageName, UserHandle user,
19339            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
19340            PackageRemovedInfo outInfo, boolean writeSettings,
19341            PackageParser.Package replacingPackage) {
19342        if (packageName == null) {
19343            Slog.w(TAG, "Attempt to delete null packageName.");
19344            return false;
19345        }
19346
19347        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
19348
19349        PackageSetting ps;
19350        synchronized (mPackages) {
19351            ps = mSettings.mPackages.get(packageName);
19352            if (ps == null) {
19353                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19354                return false;
19355            }
19356
19357            if (ps.parentPackageName != null && (!isSystemApp(ps)
19358                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
19359                if (DEBUG_REMOVE) {
19360                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
19361                            + ((user == null) ? UserHandle.USER_ALL : user));
19362                }
19363                final int removedUserId = (user != null) ? user.getIdentifier()
19364                        : UserHandle.USER_ALL;
19365                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
19366                    return false;
19367                }
19368                markPackageUninstalledForUserLPw(ps, user);
19369                scheduleWritePackageRestrictionsLocked(user);
19370                return true;
19371            }
19372        }
19373
19374        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
19375                && user.getIdentifier() != UserHandle.USER_ALL)) {
19376            // The caller is asking that the package only be deleted for a single
19377            // user.  To do this, we just mark its uninstalled state and delete
19378            // its data. If this is a system app, we only allow this to happen if
19379            // they have set the special DELETE_SYSTEM_APP which requests different
19380            // semantics than normal for uninstalling system apps.
19381            markPackageUninstalledForUserLPw(ps, user);
19382
19383            if (!isSystemApp(ps)) {
19384                // Do not uninstall the APK if an app should be cached
19385                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
19386                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
19387                    // Other user still have this package installed, so all
19388                    // we need to do is clear this user's data and save that
19389                    // it is uninstalled.
19390                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
19391                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
19392                        return false;
19393                    }
19394                    scheduleWritePackageRestrictionsLocked(user);
19395                    return true;
19396                } else {
19397                    // We need to set it back to 'installed' so the uninstall
19398                    // broadcasts will be sent correctly.
19399                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
19400                    ps.setInstalled(true, user.getIdentifier());
19401                    mSettings.writeKernelMappingLPr(ps);
19402                }
19403            } else {
19404                // This is a system app, so we assume that the
19405                // other users still have this package installed, so all
19406                // we need to do is clear this user's data and save that
19407                // it is uninstalled.
19408                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
19409                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
19410                    return false;
19411                }
19412                scheduleWritePackageRestrictionsLocked(user);
19413                return true;
19414            }
19415        }
19416
19417        // If we are deleting a composite package for all users, keep track
19418        // of result for each child.
19419        if (ps.childPackageNames != null && outInfo != null) {
19420            synchronized (mPackages) {
19421                final int childCount = ps.childPackageNames.size();
19422                outInfo.removedChildPackages = new ArrayMap<>(childCount);
19423                for (int i = 0; i < childCount; i++) {
19424                    String childPackageName = ps.childPackageNames.get(i);
19425                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
19426                    childInfo.removedPackage = childPackageName;
19427                    childInfo.installerPackageName = ps.installerPackageName;
19428                    outInfo.removedChildPackages.put(childPackageName, childInfo);
19429                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
19430                    if (childPs != null) {
19431                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
19432                    }
19433                }
19434            }
19435        }
19436
19437        boolean ret = false;
19438        if (isSystemApp(ps)) {
19439            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
19440            // When an updated system application is deleted we delete the existing resources
19441            // as well and fall back to existing code in system partition
19442            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
19443        } else {
19444            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
19445            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
19446                    outInfo, writeSettings, replacingPackage);
19447        }
19448
19449        // Take a note whether we deleted the package for all users
19450        if (outInfo != null) {
19451            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
19452            if (outInfo.removedChildPackages != null) {
19453                synchronized (mPackages) {
19454                    final int childCount = outInfo.removedChildPackages.size();
19455                    for (int i = 0; i < childCount; i++) {
19456                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
19457                        if (childInfo != null) {
19458                            childInfo.removedForAllUsers = mPackages.get(
19459                                    childInfo.removedPackage) == null;
19460                        }
19461                    }
19462                }
19463            }
19464            // If we uninstalled an update to a system app there may be some
19465            // child packages that appeared as they are declared in the system
19466            // app but were not declared in the update.
19467            if (isSystemApp(ps)) {
19468                synchronized (mPackages) {
19469                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
19470                    final int childCount = (updatedPs.childPackageNames != null)
19471                            ? updatedPs.childPackageNames.size() : 0;
19472                    for (int i = 0; i < childCount; i++) {
19473                        String childPackageName = updatedPs.childPackageNames.get(i);
19474                        if (outInfo.removedChildPackages == null
19475                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
19476                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
19477                            if (childPs == null) {
19478                                continue;
19479                            }
19480                            PackageInstalledInfo installRes = new PackageInstalledInfo();
19481                            installRes.name = childPackageName;
19482                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
19483                            installRes.pkg = mPackages.get(childPackageName);
19484                            installRes.uid = childPs.pkg.applicationInfo.uid;
19485                            if (outInfo.appearedChildPackages == null) {
19486                                outInfo.appearedChildPackages = new ArrayMap<>();
19487                            }
19488                            outInfo.appearedChildPackages.put(childPackageName, installRes);
19489                        }
19490                    }
19491                }
19492            }
19493        }
19494
19495        return ret;
19496    }
19497
19498    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
19499        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
19500                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
19501        for (int nextUserId : userIds) {
19502            if (DEBUG_REMOVE) {
19503                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
19504            }
19505            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
19506                    false /*installed*/,
19507                    true /*stopped*/,
19508                    true /*notLaunched*/,
19509                    false /*hidden*/,
19510                    false /*suspended*/,
19511                    false /*instantApp*/,
19512                    null /*lastDisableAppCaller*/,
19513                    null /*enabledComponents*/,
19514                    null /*disabledComponents*/,
19515                    ps.readUserState(nextUserId).domainVerificationStatus,
19516                    0, PackageManager.INSTALL_REASON_UNKNOWN);
19517        }
19518        mSettings.writeKernelMappingLPr(ps);
19519    }
19520
19521    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
19522            PackageRemovedInfo outInfo) {
19523        final PackageParser.Package pkg;
19524        synchronized (mPackages) {
19525            pkg = mPackages.get(ps.name);
19526        }
19527
19528        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
19529                : new int[] {userId};
19530        for (int nextUserId : userIds) {
19531            if (DEBUG_REMOVE) {
19532                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
19533                        + nextUserId);
19534            }
19535
19536            destroyAppDataLIF(pkg, userId,
19537                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19538            destroyAppProfilesLIF(pkg, userId);
19539            clearDefaultBrowserIfNeededForUser(ps.name, userId);
19540            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
19541            schedulePackageCleaning(ps.name, nextUserId, false);
19542            synchronized (mPackages) {
19543                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
19544                    scheduleWritePackageRestrictionsLocked(nextUserId);
19545                }
19546                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
19547            }
19548        }
19549
19550        if (outInfo != null) {
19551            outInfo.removedPackage = ps.name;
19552            outInfo.installerPackageName = ps.installerPackageName;
19553            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
19554            outInfo.removedAppId = ps.appId;
19555            outInfo.removedUsers = userIds;
19556            outInfo.broadcastUsers = userIds;
19557        }
19558
19559        return true;
19560    }
19561
19562    private final class ClearStorageConnection implements ServiceConnection {
19563        IMediaContainerService mContainerService;
19564
19565        @Override
19566        public void onServiceConnected(ComponentName name, IBinder service) {
19567            synchronized (this) {
19568                mContainerService = IMediaContainerService.Stub
19569                        .asInterface(Binder.allowBlocking(service));
19570                notifyAll();
19571            }
19572        }
19573
19574        @Override
19575        public void onServiceDisconnected(ComponentName name) {
19576        }
19577    }
19578
19579    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
19580        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
19581
19582        final boolean mounted;
19583        if (Environment.isExternalStorageEmulated()) {
19584            mounted = true;
19585        } else {
19586            final String status = Environment.getExternalStorageState();
19587
19588            mounted = status.equals(Environment.MEDIA_MOUNTED)
19589                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
19590        }
19591
19592        if (!mounted) {
19593            return;
19594        }
19595
19596        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
19597        int[] users;
19598        if (userId == UserHandle.USER_ALL) {
19599            users = sUserManager.getUserIds();
19600        } else {
19601            users = new int[] { userId };
19602        }
19603        final ClearStorageConnection conn = new ClearStorageConnection();
19604        if (mContext.bindServiceAsUser(
19605                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
19606            try {
19607                for (int curUser : users) {
19608                    long timeout = SystemClock.uptimeMillis() + 5000;
19609                    synchronized (conn) {
19610                        long now;
19611                        while (conn.mContainerService == null &&
19612                                (now = SystemClock.uptimeMillis()) < timeout) {
19613                            try {
19614                                conn.wait(timeout - now);
19615                            } catch (InterruptedException e) {
19616                            }
19617                        }
19618                    }
19619                    if (conn.mContainerService == null) {
19620                        return;
19621                    }
19622
19623                    final UserEnvironment userEnv = new UserEnvironment(curUser);
19624                    clearDirectory(conn.mContainerService,
19625                            userEnv.buildExternalStorageAppCacheDirs(packageName));
19626                    if (allData) {
19627                        clearDirectory(conn.mContainerService,
19628                                userEnv.buildExternalStorageAppDataDirs(packageName));
19629                        clearDirectory(conn.mContainerService,
19630                                userEnv.buildExternalStorageAppMediaDirs(packageName));
19631                    }
19632                }
19633            } finally {
19634                mContext.unbindService(conn);
19635            }
19636        }
19637    }
19638
19639    @Override
19640    public void clearApplicationProfileData(String packageName) {
19641        enforceSystemOrRoot("Only the system can clear all profile data");
19642
19643        final PackageParser.Package pkg;
19644        synchronized (mPackages) {
19645            pkg = mPackages.get(packageName);
19646        }
19647
19648        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
19649            synchronized (mInstallLock) {
19650                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
19651            }
19652        }
19653    }
19654
19655    @Override
19656    public void clearApplicationUserData(final String packageName,
19657            final IPackageDataObserver observer, final int userId) {
19658        mContext.enforceCallingOrSelfPermission(
19659                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
19660
19661        final int callingUid = Binder.getCallingUid();
19662        enforceCrossUserPermission(callingUid, userId,
19663                true /* requireFullPermission */, false /* checkShell */, "clear application data");
19664
19665        final PackageSetting ps = mSettings.getPackageLPr(packageName);
19666        if (ps != null && filterAppAccessLPr(ps, callingUid, userId)) {
19667            return;
19668        }
19669        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
19670            throw new SecurityException("Cannot clear data for a protected package: "
19671                    + packageName);
19672        }
19673        // Queue up an async operation since the package deletion may take a little while.
19674        mHandler.post(new Runnable() {
19675            public void run() {
19676                mHandler.removeCallbacks(this);
19677                final boolean succeeded;
19678                try (PackageFreezer freezer = freezePackage(packageName,
19679                        "clearApplicationUserData")) {
19680                    synchronized (mInstallLock) {
19681                        succeeded = clearApplicationUserDataLIF(packageName, userId);
19682                    }
19683                    clearExternalStorageDataSync(packageName, userId, true);
19684                    synchronized (mPackages) {
19685                        mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
19686                                packageName, userId);
19687                    }
19688                }
19689                if (succeeded) {
19690                    // invoke DeviceStorageMonitor's update method to clear any notifications
19691                    DeviceStorageMonitorInternal dsm = LocalServices
19692                            .getService(DeviceStorageMonitorInternal.class);
19693                    if (dsm != null) {
19694                        dsm.checkMemory();
19695                    }
19696                }
19697                if(observer != null) {
19698                    try {
19699                        observer.onRemoveCompleted(packageName, succeeded);
19700                    } catch (RemoteException e) {
19701                        Log.i(TAG, "Observer no longer exists.");
19702                    }
19703                } //end if observer
19704            } //end run
19705        });
19706    }
19707
19708    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
19709        if (packageName == null) {
19710            Slog.w(TAG, "Attempt to delete null packageName.");
19711            return false;
19712        }
19713
19714        // Try finding details about the requested package
19715        PackageParser.Package pkg;
19716        synchronized (mPackages) {
19717            pkg = mPackages.get(packageName);
19718            if (pkg == null) {
19719                final PackageSetting ps = mSettings.mPackages.get(packageName);
19720                if (ps != null) {
19721                    pkg = ps.pkg;
19722                }
19723            }
19724
19725            if (pkg == null) {
19726                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19727                return false;
19728            }
19729
19730            PackageSetting ps = (PackageSetting) pkg.mExtras;
19731            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19732        }
19733
19734        clearAppDataLIF(pkg, userId,
19735                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19736
19737        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
19738        removeKeystoreDataIfNeeded(userId, appId);
19739
19740        UserManagerInternal umInternal = getUserManagerInternal();
19741        final int flags;
19742        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
19743            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19744        } else if (umInternal.isUserRunning(userId)) {
19745            flags = StorageManager.FLAG_STORAGE_DE;
19746        } else {
19747            flags = 0;
19748        }
19749        prepareAppDataContentsLIF(pkg, userId, flags);
19750
19751        return true;
19752    }
19753
19754    /**
19755     * Reverts user permission state changes (permissions and flags) in
19756     * all packages for a given user.
19757     *
19758     * @param userId The device user for which to do a reset.
19759     */
19760    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
19761        final int packageCount = mPackages.size();
19762        for (int i = 0; i < packageCount; i++) {
19763            PackageParser.Package pkg = mPackages.valueAt(i);
19764            PackageSetting ps = (PackageSetting) pkg.mExtras;
19765            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19766        }
19767    }
19768
19769    private void resetNetworkPolicies(int userId) {
19770        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
19771    }
19772
19773    /**
19774     * Reverts user permission state changes (permissions and flags).
19775     *
19776     * @param ps The package for which to reset.
19777     * @param userId The device user for which to do a reset.
19778     */
19779    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
19780            final PackageSetting ps, final int userId) {
19781        if (ps.pkg == null) {
19782            return;
19783        }
19784
19785        // These are flags that can change base on user actions.
19786        final int userSettableMask = FLAG_PERMISSION_USER_SET
19787                | FLAG_PERMISSION_USER_FIXED
19788                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
19789                | FLAG_PERMISSION_REVIEW_REQUIRED;
19790
19791        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
19792                | FLAG_PERMISSION_POLICY_FIXED;
19793
19794        boolean writeInstallPermissions = false;
19795        boolean writeRuntimePermissions = false;
19796
19797        final int permissionCount = ps.pkg.requestedPermissions.size();
19798        for (int i = 0; i < permissionCount; i++) {
19799            String permission = ps.pkg.requestedPermissions.get(i);
19800
19801            BasePermission bp = mSettings.mPermissions.get(permission);
19802            if (bp == null) {
19803                continue;
19804            }
19805
19806            // If shared user we just reset the state to which only this app contributed.
19807            if (ps.sharedUser != null) {
19808                boolean used = false;
19809                final int packageCount = ps.sharedUser.packages.size();
19810                for (int j = 0; j < packageCount; j++) {
19811                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
19812                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
19813                            && pkg.pkg.requestedPermissions.contains(permission)) {
19814                        used = true;
19815                        break;
19816                    }
19817                }
19818                if (used) {
19819                    continue;
19820                }
19821            }
19822
19823            PermissionsState permissionsState = ps.getPermissionsState();
19824
19825            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
19826
19827            // Always clear the user settable flags.
19828            final boolean hasInstallState = permissionsState.getInstallPermissionState(
19829                    bp.name) != null;
19830            // If permission review is enabled and this is a legacy app, mark the
19831            // permission as requiring a review as this is the initial state.
19832            int flags = 0;
19833            if (mPermissionReviewRequired
19834                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
19835                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
19836            }
19837            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
19838                if (hasInstallState) {
19839                    writeInstallPermissions = true;
19840                } else {
19841                    writeRuntimePermissions = true;
19842                }
19843            }
19844
19845            // Below is only runtime permission handling.
19846            if (!bp.isRuntime()) {
19847                continue;
19848            }
19849
19850            // Never clobber system or policy.
19851            if ((oldFlags & policyOrSystemFlags) != 0) {
19852                continue;
19853            }
19854
19855            // If this permission was granted by default, make sure it is.
19856            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
19857                if (permissionsState.grantRuntimePermission(bp, userId)
19858                        != PERMISSION_OPERATION_FAILURE) {
19859                    writeRuntimePermissions = true;
19860                }
19861            // If permission review is enabled the permissions for a legacy apps
19862            // are represented as constantly granted runtime ones, so don't revoke.
19863            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
19864                // Otherwise, reset the permission.
19865                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
19866                switch (revokeResult) {
19867                    case PERMISSION_OPERATION_SUCCESS:
19868                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
19869                        writeRuntimePermissions = true;
19870                        final int appId = ps.appId;
19871                        mHandler.post(new Runnable() {
19872                            @Override
19873                            public void run() {
19874                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
19875                            }
19876                        });
19877                    } break;
19878                }
19879            }
19880        }
19881
19882        // Synchronously write as we are taking permissions away.
19883        if (writeRuntimePermissions) {
19884            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
19885        }
19886
19887        // Synchronously write as we are taking permissions away.
19888        if (writeInstallPermissions) {
19889            mSettings.writeLPr();
19890        }
19891    }
19892
19893    /**
19894     * Remove entries from the keystore daemon. Will only remove it if the
19895     * {@code appId} is valid.
19896     */
19897    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
19898        if (appId < 0) {
19899            return;
19900        }
19901
19902        final KeyStore keyStore = KeyStore.getInstance();
19903        if (keyStore != null) {
19904            if (userId == UserHandle.USER_ALL) {
19905                for (final int individual : sUserManager.getUserIds()) {
19906                    keyStore.clearUid(UserHandle.getUid(individual, appId));
19907                }
19908            } else {
19909                keyStore.clearUid(UserHandle.getUid(userId, appId));
19910            }
19911        } else {
19912            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
19913        }
19914    }
19915
19916    @Override
19917    public void deleteApplicationCacheFiles(final String packageName,
19918            final IPackageDataObserver observer) {
19919        final int userId = UserHandle.getCallingUserId();
19920        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
19921    }
19922
19923    @Override
19924    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
19925            final IPackageDataObserver observer) {
19926        final int callingUid = Binder.getCallingUid();
19927        mContext.enforceCallingOrSelfPermission(
19928                android.Manifest.permission.DELETE_CACHE_FILES, null);
19929        enforceCrossUserPermission(callingUid, userId,
19930                /* requireFullPermission= */ true, /* checkShell= */ false,
19931                "delete application cache files");
19932        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
19933                android.Manifest.permission.ACCESS_INSTANT_APPS);
19934
19935        final PackageParser.Package pkg;
19936        synchronized (mPackages) {
19937            pkg = mPackages.get(packageName);
19938        }
19939
19940        // Queue up an async operation since the package deletion may take a little while.
19941        mHandler.post(new Runnable() {
19942            public void run() {
19943                final PackageSetting ps = (PackageSetting) pkg.mExtras;
19944                boolean doClearData = true;
19945                if (ps != null) {
19946                    final boolean targetIsInstantApp =
19947                            ps.getInstantApp(UserHandle.getUserId(callingUid));
19948                    doClearData = !targetIsInstantApp
19949                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
19950                }
19951                if (doClearData) {
19952                    synchronized (mInstallLock) {
19953                        final int flags = StorageManager.FLAG_STORAGE_DE
19954                                | StorageManager.FLAG_STORAGE_CE;
19955                        // We're only clearing cache files, so we don't care if the
19956                        // app is unfrozen and still able to run
19957                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
19958                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19959                    }
19960                    clearExternalStorageDataSync(packageName, userId, false);
19961                }
19962                if (observer != null) {
19963                    try {
19964                        observer.onRemoveCompleted(packageName, true);
19965                    } catch (RemoteException e) {
19966                        Log.i(TAG, "Observer no longer exists.");
19967                    }
19968                }
19969            }
19970        });
19971    }
19972
19973    @Override
19974    public void getPackageSizeInfo(final String packageName, int userHandle,
19975            final IPackageStatsObserver observer) {
19976        throw new UnsupportedOperationException(
19977                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
19978    }
19979
19980    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
19981        final PackageSetting ps;
19982        synchronized (mPackages) {
19983            ps = mSettings.mPackages.get(packageName);
19984            if (ps == null) {
19985                Slog.w(TAG, "Failed to find settings for " + packageName);
19986                return false;
19987            }
19988        }
19989
19990        final String[] packageNames = { packageName };
19991        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
19992        final String[] codePaths = { ps.codePathString };
19993
19994        try {
19995            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
19996                    ps.appId, ceDataInodes, codePaths, stats);
19997
19998            // For now, ignore code size of packages on system partition
19999            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
20000                stats.codeSize = 0;
20001            }
20002
20003            // External clients expect these to be tracked separately
20004            stats.dataSize -= stats.cacheSize;
20005
20006        } catch (InstallerException e) {
20007            Slog.w(TAG, String.valueOf(e));
20008            return false;
20009        }
20010
20011        return true;
20012    }
20013
20014    private int getUidTargetSdkVersionLockedLPr(int uid) {
20015        Object obj = mSettings.getUserIdLPr(uid);
20016        if (obj instanceof SharedUserSetting) {
20017            final SharedUserSetting sus = (SharedUserSetting) obj;
20018            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
20019            final Iterator<PackageSetting> it = sus.packages.iterator();
20020            while (it.hasNext()) {
20021                final PackageSetting ps = it.next();
20022                if (ps.pkg != null) {
20023                    int v = ps.pkg.applicationInfo.targetSdkVersion;
20024                    if (v < vers) vers = v;
20025                }
20026            }
20027            return vers;
20028        } else if (obj instanceof PackageSetting) {
20029            final PackageSetting ps = (PackageSetting) obj;
20030            if (ps.pkg != null) {
20031                return ps.pkg.applicationInfo.targetSdkVersion;
20032            }
20033        }
20034        return Build.VERSION_CODES.CUR_DEVELOPMENT;
20035    }
20036
20037    @Override
20038    public void addPreferredActivity(IntentFilter filter, int match,
20039            ComponentName[] set, ComponentName activity, int userId) {
20040        addPreferredActivityInternal(filter, match, set, activity, true, userId,
20041                "Adding preferred");
20042    }
20043
20044    private void addPreferredActivityInternal(IntentFilter filter, int match,
20045            ComponentName[] set, ComponentName activity, boolean always, int userId,
20046            String opname) {
20047        // writer
20048        int callingUid = Binder.getCallingUid();
20049        enforceCrossUserPermission(callingUid, userId,
20050                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
20051        if (filter.countActions() == 0) {
20052            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20053            return;
20054        }
20055        synchronized (mPackages) {
20056            if (mContext.checkCallingOrSelfPermission(
20057                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20058                    != PackageManager.PERMISSION_GRANTED) {
20059                if (getUidTargetSdkVersionLockedLPr(callingUid)
20060                        < Build.VERSION_CODES.FROYO) {
20061                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
20062                            + callingUid);
20063                    return;
20064                }
20065                mContext.enforceCallingOrSelfPermission(
20066                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20067            }
20068
20069            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
20070            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
20071                    + userId + ":");
20072            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20073            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
20074            scheduleWritePackageRestrictionsLocked(userId);
20075            postPreferredActivityChangedBroadcast(userId);
20076        }
20077    }
20078
20079    private void postPreferredActivityChangedBroadcast(int userId) {
20080        mHandler.post(() -> {
20081            final IActivityManager am = ActivityManager.getService();
20082            if (am == null) {
20083                return;
20084            }
20085
20086            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
20087            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
20088            try {
20089                am.broadcastIntent(null, intent, null, null,
20090                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
20091                        null, false, false, userId);
20092            } catch (RemoteException e) {
20093            }
20094        });
20095    }
20096
20097    @Override
20098    public void replacePreferredActivity(IntentFilter filter, int match,
20099            ComponentName[] set, ComponentName activity, int userId) {
20100        if (filter.countActions() != 1) {
20101            throw new IllegalArgumentException(
20102                    "replacePreferredActivity expects filter to have only 1 action.");
20103        }
20104        if (filter.countDataAuthorities() != 0
20105                || filter.countDataPaths() != 0
20106                || filter.countDataSchemes() > 1
20107                || filter.countDataTypes() != 0) {
20108            throw new IllegalArgumentException(
20109                    "replacePreferredActivity expects filter to have no data authorities, " +
20110                    "paths, or types; and at most one scheme.");
20111        }
20112
20113        final int callingUid = Binder.getCallingUid();
20114        enforceCrossUserPermission(callingUid, userId,
20115                true /* requireFullPermission */, false /* checkShell */,
20116                "replace preferred activity");
20117        synchronized (mPackages) {
20118            if (mContext.checkCallingOrSelfPermission(
20119                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20120                    != PackageManager.PERMISSION_GRANTED) {
20121                if (getUidTargetSdkVersionLockedLPr(callingUid)
20122                        < Build.VERSION_CODES.FROYO) {
20123                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
20124                            + Binder.getCallingUid());
20125                    return;
20126                }
20127                mContext.enforceCallingOrSelfPermission(
20128                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20129            }
20130
20131            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20132            if (pir != null) {
20133                // Get all of the existing entries that exactly match this filter.
20134                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
20135                if (existing != null && existing.size() == 1) {
20136                    PreferredActivity cur = existing.get(0);
20137                    if (DEBUG_PREFERRED) {
20138                        Slog.i(TAG, "Checking replace of preferred:");
20139                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20140                        if (!cur.mPref.mAlways) {
20141                            Slog.i(TAG, "  -- CUR; not mAlways!");
20142                        } else {
20143                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
20144                            Slog.i(TAG, "  -- CUR: mSet="
20145                                    + Arrays.toString(cur.mPref.mSetComponents));
20146                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
20147                            Slog.i(TAG, "  -- NEW: mMatch="
20148                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
20149                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
20150                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
20151                        }
20152                    }
20153                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
20154                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
20155                            && cur.mPref.sameSet(set)) {
20156                        // Setting the preferred activity to what it happens to be already
20157                        if (DEBUG_PREFERRED) {
20158                            Slog.i(TAG, "Replacing with same preferred activity "
20159                                    + cur.mPref.mShortComponent + " for user "
20160                                    + userId + ":");
20161                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20162                        }
20163                        return;
20164                    }
20165                }
20166
20167                if (existing != null) {
20168                    if (DEBUG_PREFERRED) {
20169                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
20170                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20171                    }
20172                    for (int i = 0; i < existing.size(); i++) {
20173                        PreferredActivity pa = existing.get(i);
20174                        if (DEBUG_PREFERRED) {
20175                            Slog.i(TAG, "Removing existing preferred activity "
20176                                    + pa.mPref.mComponent + ":");
20177                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
20178                        }
20179                        pir.removeFilter(pa);
20180                    }
20181                }
20182            }
20183            addPreferredActivityInternal(filter, match, set, activity, true, userId,
20184                    "Replacing preferred");
20185        }
20186    }
20187
20188    @Override
20189    public void clearPackagePreferredActivities(String packageName) {
20190        final int callingUid = Binder.getCallingUid();
20191        if (getInstantAppPackageName(callingUid) != null) {
20192            return;
20193        }
20194        // writer
20195        synchronized (mPackages) {
20196            PackageParser.Package pkg = mPackages.get(packageName);
20197            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
20198                if (mContext.checkCallingOrSelfPermission(
20199                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20200                        != PackageManager.PERMISSION_GRANTED) {
20201                    if (getUidTargetSdkVersionLockedLPr(callingUid)
20202                            < Build.VERSION_CODES.FROYO) {
20203                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
20204                                + callingUid);
20205                        return;
20206                    }
20207                    mContext.enforceCallingOrSelfPermission(
20208                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20209                }
20210            }
20211            final PackageSetting ps = mSettings.getPackageLPr(packageName);
20212            if (ps != null
20213                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20214                return;
20215            }
20216            int user = UserHandle.getCallingUserId();
20217            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
20218                scheduleWritePackageRestrictionsLocked(user);
20219            }
20220        }
20221    }
20222
20223    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20224    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
20225        ArrayList<PreferredActivity> removed = null;
20226        boolean changed = false;
20227        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20228            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
20229            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20230            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
20231                continue;
20232            }
20233            Iterator<PreferredActivity> it = pir.filterIterator();
20234            while (it.hasNext()) {
20235                PreferredActivity pa = it.next();
20236                // Mark entry for removal only if it matches the package name
20237                // and the entry is of type "always".
20238                if (packageName == null ||
20239                        (pa.mPref.mComponent.getPackageName().equals(packageName)
20240                                && pa.mPref.mAlways)) {
20241                    if (removed == null) {
20242                        removed = new ArrayList<PreferredActivity>();
20243                    }
20244                    removed.add(pa);
20245                }
20246            }
20247            if (removed != null) {
20248                for (int j=0; j<removed.size(); j++) {
20249                    PreferredActivity pa = removed.get(j);
20250                    pir.removeFilter(pa);
20251                }
20252                changed = true;
20253            }
20254        }
20255        if (changed) {
20256            postPreferredActivityChangedBroadcast(userId);
20257        }
20258        return changed;
20259    }
20260
20261    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20262    private void clearIntentFilterVerificationsLPw(int userId) {
20263        final int packageCount = mPackages.size();
20264        for (int i = 0; i < packageCount; i++) {
20265            PackageParser.Package pkg = mPackages.valueAt(i);
20266            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
20267        }
20268    }
20269
20270    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20271    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
20272        if (userId == UserHandle.USER_ALL) {
20273            if (mSettings.removeIntentFilterVerificationLPw(packageName,
20274                    sUserManager.getUserIds())) {
20275                for (int oneUserId : sUserManager.getUserIds()) {
20276                    scheduleWritePackageRestrictionsLocked(oneUserId);
20277                }
20278            }
20279        } else {
20280            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
20281                scheduleWritePackageRestrictionsLocked(userId);
20282            }
20283        }
20284    }
20285
20286    /** Clears state for all users, and touches intent filter verification policy */
20287    void clearDefaultBrowserIfNeeded(String packageName) {
20288        for (int oneUserId : sUserManager.getUserIds()) {
20289            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
20290        }
20291    }
20292
20293    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
20294        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
20295        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
20296            if (packageName.equals(defaultBrowserPackageName)) {
20297                setDefaultBrowserPackageName(null, userId);
20298            }
20299        }
20300    }
20301
20302    @Override
20303    public void resetApplicationPreferences(int userId) {
20304        mContext.enforceCallingOrSelfPermission(
20305                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20306        final long identity = Binder.clearCallingIdentity();
20307        // writer
20308        try {
20309            synchronized (mPackages) {
20310                clearPackagePreferredActivitiesLPw(null, userId);
20311                mSettings.applyDefaultPreferredAppsLPw(this, userId);
20312                // TODO: We have to reset the default SMS and Phone. This requires
20313                // significant refactoring to keep all default apps in the package
20314                // manager (cleaner but more work) or have the services provide
20315                // callbacks to the package manager to request a default app reset.
20316                applyFactoryDefaultBrowserLPw(userId);
20317                clearIntentFilterVerificationsLPw(userId);
20318                primeDomainVerificationsLPw(userId);
20319                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
20320                scheduleWritePackageRestrictionsLocked(userId);
20321            }
20322            resetNetworkPolicies(userId);
20323        } finally {
20324            Binder.restoreCallingIdentity(identity);
20325        }
20326    }
20327
20328    @Override
20329    public int getPreferredActivities(List<IntentFilter> outFilters,
20330            List<ComponentName> outActivities, String packageName) {
20331        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20332            return 0;
20333        }
20334        int num = 0;
20335        final int userId = UserHandle.getCallingUserId();
20336        // reader
20337        synchronized (mPackages) {
20338            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20339            if (pir != null) {
20340                final Iterator<PreferredActivity> it = pir.filterIterator();
20341                while (it.hasNext()) {
20342                    final PreferredActivity pa = it.next();
20343                    if (packageName == null
20344                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
20345                                    && pa.mPref.mAlways)) {
20346                        if (outFilters != null) {
20347                            outFilters.add(new IntentFilter(pa));
20348                        }
20349                        if (outActivities != null) {
20350                            outActivities.add(pa.mPref.mComponent);
20351                        }
20352                    }
20353                }
20354            }
20355        }
20356
20357        return num;
20358    }
20359
20360    @Override
20361    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
20362            int userId) {
20363        int callingUid = Binder.getCallingUid();
20364        if (callingUid != Process.SYSTEM_UID) {
20365            throw new SecurityException(
20366                    "addPersistentPreferredActivity can only be run by the system");
20367        }
20368        if (filter.countActions() == 0) {
20369            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20370            return;
20371        }
20372        synchronized (mPackages) {
20373            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
20374                    ":");
20375            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20376            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
20377                    new PersistentPreferredActivity(filter, activity));
20378            scheduleWritePackageRestrictionsLocked(userId);
20379            postPreferredActivityChangedBroadcast(userId);
20380        }
20381    }
20382
20383    @Override
20384    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
20385        int callingUid = Binder.getCallingUid();
20386        if (callingUid != Process.SYSTEM_UID) {
20387            throw new SecurityException(
20388                    "clearPackagePersistentPreferredActivities can only be run by the system");
20389        }
20390        ArrayList<PersistentPreferredActivity> removed = null;
20391        boolean changed = false;
20392        synchronized (mPackages) {
20393            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
20394                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
20395                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
20396                        .valueAt(i);
20397                if (userId != thisUserId) {
20398                    continue;
20399                }
20400                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
20401                while (it.hasNext()) {
20402                    PersistentPreferredActivity ppa = it.next();
20403                    // Mark entry for removal only if it matches the package name.
20404                    if (ppa.mComponent.getPackageName().equals(packageName)) {
20405                        if (removed == null) {
20406                            removed = new ArrayList<PersistentPreferredActivity>();
20407                        }
20408                        removed.add(ppa);
20409                    }
20410                }
20411                if (removed != null) {
20412                    for (int j=0; j<removed.size(); j++) {
20413                        PersistentPreferredActivity ppa = removed.get(j);
20414                        ppir.removeFilter(ppa);
20415                    }
20416                    changed = true;
20417                }
20418            }
20419
20420            if (changed) {
20421                scheduleWritePackageRestrictionsLocked(userId);
20422                postPreferredActivityChangedBroadcast(userId);
20423            }
20424        }
20425    }
20426
20427    /**
20428     * Common machinery for picking apart a restored XML blob and passing
20429     * it to a caller-supplied functor to be applied to the running system.
20430     */
20431    private void restoreFromXml(XmlPullParser parser, int userId,
20432            String expectedStartTag, BlobXmlRestorer functor)
20433            throws IOException, XmlPullParserException {
20434        int type;
20435        while ((type = parser.next()) != XmlPullParser.START_TAG
20436                && type != XmlPullParser.END_DOCUMENT) {
20437        }
20438        if (type != XmlPullParser.START_TAG) {
20439            // oops didn't find a start tag?!
20440            if (DEBUG_BACKUP) {
20441                Slog.e(TAG, "Didn't find start tag during restore");
20442            }
20443            return;
20444        }
20445Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
20446        // this is supposed to be TAG_PREFERRED_BACKUP
20447        if (!expectedStartTag.equals(parser.getName())) {
20448            if (DEBUG_BACKUP) {
20449                Slog.e(TAG, "Found unexpected tag " + parser.getName());
20450            }
20451            return;
20452        }
20453
20454        // skip interfering stuff, then we're aligned with the backing implementation
20455        while ((type = parser.next()) == XmlPullParser.TEXT) { }
20456Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
20457        functor.apply(parser, userId);
20458    }
20459
20460    private interface BlobXmlRestorer {
20461        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
20462    }
20463
20464    /**
20465     * Non-Binder method, support for the backup/restore mechanism: write the
20466     * full set of preferred activities in its canonical XML format.  Returns the
20467     * XML output as a byte array, or null if there is none.
20468     */
20469    @Override
20470    public byte[] getPreferredActivityBackup(int userId) {
20471        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20472            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
20473        }
20474
20475        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20476        try {
20477            final XmlSerializer serializer = new FastXmlSerializer();
20478            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20479            serializer.startDocument(null, true);
20480            serializer.startTag(null, TAG_PREFERRED_BACKUP);
20481
20482            synchronized (mPackages) {
20483                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
20484            }
20485
20486            serializer.endTag(null, TAG_PREFERRED_BACKUP);
20487            serializer.endDocument();
20488            serializer.flush();
20489        } catch (Exception e) {
20490            if (DEBUG_BACKUP) {
20491                Slog.e(TAG, "Unable to write preferred activities for backup", e);
20492            }
20493            return null;
20494        }
20495
20496        return dataStream.toByteArray();
20497    }
20498
20499    @Override
20500    public void restorePreferredActivities(byte[] backup, int userId) {
20501        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20502            throw new SecurityException("Only the system may call restorePreferredActivities()");
20503        }
20504
20505        try {
20506            final XmlPullParser parser = Xml.newPullParser();
20507            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20508            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
20509                    new BlobXmlRestorer() {
20510                        @Override
20511                        public void apply(XmlPullParser parser, int userId)
20512                                throws XmlPullParserException, IOException {
20513                            synchronized (mPackages) {
20514                                mSettings.readPreferredActivitiesLPw(parser, userId);
20515                            }
20516                        }
20517                    } );
20518        } catch (Exception e) {
20519            if (DEBUG_BACKUP) {
20520                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20521            }
20522        }
20523    }
20524
20525    /**
20526     * Non-Binder method, support for the backup/restore mechanism: write the
20527     * default browser (etc) settings in its canonical XML format.  Returns the default
20528     * browser XML representation as a byte array, or null if there is none.
20529     */
20530    @Override
20531    public byte[] getDefaultAppsBackup(int userId) {
20532        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20533            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
20534        }
20535
20536        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20537        try {
20538            final XmlSerializer serializer = new FastXmlSerializer();
20539            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20540            serializer.startDocument(null, true);
20541            serializer.startTag(null, TAG_DEFAULT_APPS);
20542
20543            synchronized (mPackages) {
20544                mSettings.writeDefaultAppsLPr(serializer, userId);
20545            }
20546
20547            serializer.endTag(null, TAG_DEFAULT_APPS);
20548            serializer.endDocument();
20549            serializer.flush();
20550        } catch (Exception e) {
20551            if (DEBUG_BACKUP) {
20552                Slog.e(TAG, "Unable to write default apps for backup", e);
20553            }
20554            return null;
20555        }
20556
20557        return dataStream.toByteArray();
20558    }
20559
20560    @Override
20561    public void restoreDefaultApps(byte[] backup, int userId) {
20562        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20563            throw new SecurityException("Only the system may call restoreDefaultApps()");
20564        }
20565
20566        try {
20567            final XmlPullParser parser = Xml.newPullParser();
20568            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20569            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
20570                    new BlobXmlRestorer() {
20571                        @Override
20572                        public void apply(XmlPullParser parser, int userId)
20573                                throws XmlPullParserException, IOException {
20574                            synchronized (mPackages) {
20575                                mSettings.readDefaultAppsLPw(parser, userId);
20576                            }
20577                        }
20578                    } );
20579        } catch (Exception e) {
20580            if (DEBUG_BACKUP) {
20581                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
20582            }
20583        }
20584    }
20585
20586    @Override
20587    public byte[] getIntentFilterVerificationBackup(int userId) {
20588        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20589            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
20590        }
20591
20592        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20593        try {
20594            final XmlSerializer serializer = new FastXmlSerializer();
20595            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20596            serializer.startDocument(null, true);
20597            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
20598
20599            synchronized (mPackages) {
20600                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
20601            }
20602
20603            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
20604            serializer.endDocument();
20605            serializer.flush();
20606        } catch (Exception e) {
20607            if (DEBUG_BACKUP) {
20608                Slog.e(TAG, "Unable to write default apps for backup", e);
20609            }
20610            return null;
20611        }
20612
20613        return dataStream.toByteArray();
20614    }
20615
20616    @Override
20617    public void restoreIntentFilterVerification(byte[] backup, int userId) {
20618        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20619            throw new SecurityException("Only the system may call restorePreferredActivities()");
20620        }
20621
20622        try {
20623            final XmlPullParser parser = Xml.newPullParser();
20624            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20625            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
20626                    new BlobXmlRestorer() {
20627                        @Override
20628                        public void apply(XmlPullParser parser, int userId)
20629                                throws XmlPullParserException, IOException {
20630                            synchronized (mPackages) {
20631                                mSettings.readAllDomainVerificationsLPr(parser, userId);
20632                                mSettings.writeLPr();
20633                            }
20634                        }
20635                    } );
20636        } catch (Exception e) {
20637            if (DEBUG_BACKUP) {
20638                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20639            }
20640        }
20641    }
20642
20643    @Override
20644    public byte[] getPermissionGrantBackup(int userId) {
20645        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20646            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
20647        }
20648
20649        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20650        try {
20651            final XmlSerializer serializer = new FastXmlSerializer();
20652            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20653            serializer.startDocument(null, true);
20654            serializer.startTag(null, TAG_PERMISSION_BACKUP);
20655
20656            synchronized (mPackages) {
20657                serializeRuntimePermissionGrantsLPr(serializer, userId);
20658            }
20659
20660            serializer.endTag(null, TAG_PERMISSION_BACKUP);
20661            serializer.endDocument();
20662            serializer.flush();
20663        } catch (Exception e) {
20664            if (DEBUG_BACKUP) {
20665                Slog.e(TAG, "Unable to write default apps for backup", e);
20666            }
20667            return null;
20668        }
20669
20670        return dataStream.toByteArray();
20671    }
20672
20673    @Override
20674    public void restorePermissionGrants(byte[] backup, int userId) {
20675        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20676            throw new SecurityException("Only the system may call restorePermissionGrants()");
20677        }
20678
20679        try {
20680            final XmlPullParser parser = Xml.newPullParser();
20681            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20682            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
20683                    new BlobXmlRestorer() {
20684                        @Override
20685                        public void apply(XmlPullParser parser, int userId)
20686                                throws XmlPullParserException, IOException {
20687                            synchronized (mPackages) {
20688                                processRestoredPermissionGrantsLPr(parser, userId);
20689                            }
20690                        }
20691                    } );
20692        } catch (Exception e) {
20693            if (DEBUG_BACKUP) {
20694                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20695            }
20696        }
20697    }
20698
20699    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
20700            throws IOException {
20701        serializer.startTag(null, TAG_ALL_GRANTS);
20702
20703        final int N = mSettings.mPackages.size();
20704        for (int i = 0; i < N; i++) {
20705            final PackageSetting ps = mSettings.mPackages.valueAt(i);
20706            boolean pkgGrantsKnown = false;
20707
20708            PermissionsState packagePerms = ps.getPermissionsState();
20709
20710            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
20711                final int grantFlags = state.getFlags();
20712                // only look at grants that are not system/policy fixed
20713                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
20714                    final boolean isGranted = state.isGranted();
20715                    // And only back up the user-twiddled state bits
20716                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
20717                        final String packageName = mSettings.mPackages.keyAt(i);
20718                        if (!pkgGrantsKnown) {
20719                            serializer.startTag(null, TAG_GRANT);
20720                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
20721                            pkgGrantsKnown = true;
20722                        }
20723
20724                        final boolean userSet =
20725                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
20726                        final boolean userFixed =
20727                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
20728                        final boolean revoke =
20729                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
20730
20731                        serializer.startTag(null, TAG_PERMISSION);
20732                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
20733                        if (isGranted) {
20734                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
20735                        }
20736                        if (userSet) {
20737                            serializer.attribute(null, ATTR_USER_SET, "true");
20738                        }
20739                        if (userFixed) {
20740                            serializer.attribute(null, ATTR_USER_FIXED, "true");
20741                        }
20742                        if (revoke) {
20743                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
20744                        }
20745                        serializer.endTag(null, TAG_PERMISSION);
20746                    }
20747                }
20748            }
20749
20750            if (pkgGrantsKnown) {
20751                serializer.endTag(null, TAG_GRANT);
20752            }
20753        }
20754
20755        serializer.endTag(null, TAG_ALL_GRANTS);
20756    }
20757
20758    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
20759            throws XmlPullParserException, IOException {
20760        String pkgName = null;
20761        int outerDepth = parser.getDepth();
20762        int type;
20763        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
20764                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
20765            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
20766                continue;
20767            }
20768
20769            final String tagName = parser.getName();
20770            if (tagName.equals(TAG_GRANT)) {
20771                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
20772                if (DEBUG_BACKUP) {
20773                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
20774                }
20775            } else if (tagName.equals(TAG_PERMISSION)) {
20776
20777                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
20778                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
20779
20780                int newFlagSet = 0;
20781                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
20782                    newFlagSet |= FLAG_PERMISSION_USER_SET;
20783                }
20784                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
20785                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
20786                }
20787                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
20788                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
20789                }
20790                if (DEBUG_BACKUP) {
20791                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
20792                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
20793                }
20794                final PackageSetting ps = mSettings.mPackages.get(pkgName);
20795                if (ps != null) {
20796                    // Already installed so we apply the grant immediately
20797                    if (DEBUG_BACKUP) {
20798                        Slog.v(TAG, "        + already installed; applying");
20799                    }
20800                    PermissionsState perms = ps.getPermissionsState();
20801                    BasePermission bp = mSettings.mPermissions.get(permName);
20802                    if (bp != null) {
20803                        if (isGranted) {
20804                            perms.grantRuntimePermission(bp, userId);
20805                        }
20806                        if (newFlagSet != 0) {
20807                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
20808                        }
20809                    }
20810                } else {
20811                    // Need to wait for post-restore install to apply the grant
20812                    if (DEBUG_BACKUP) {
20813                        Slog.v(TAG, "        - not yet installed; saving for later");
20814                    }
20815                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
20816                            isGranted, newFlagSet, userId);
20817                }
20818            } else {
20819                PackageManagerService.reportSettingsProblem(Log.WARN,
20820                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
20821                XmlUtils.skipCurrentTag(parser);
20822            }
20823        }
20824
20825        scheduleWriteSettingsLocked();
20826        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
20827    }
20828
20829    @Override
20830    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
20831            int sourceUserId, int targetUserId, int flags) {
20832        mContext.enforceCallingOrSelfPermission(
20833                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20834        int callingUid = Binder.getCallingUid();
20835        enforceOwnerRights(ownerPackage, callingUid);
20836        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20837        if (intentFilter.countActions() == 0) {
20838            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
20839            return;
20840        }
20841        synchronized (mPackages) {
20842            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
20843                    ownerPackage, targetUserId, flags);
20844            CrossProfileIntentResolver resolver =
20845                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20846            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
20847            // We have all those whose filter is equal. Now checking if the rest is equal as well.
20848            if (existing != null) {
20849                int size = existing.size();
20850                for (int i = 0; i < size; i++) {
20851                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
20852                        return;
20853                    }
20854                }
20855            }
20856            resolver.addFilter(newFilter);
20857            scheduleWritePackageRestrictionsLocked(sourceUserId);
20858        }
20859    }
20860
20861    @Override
20862    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
20863        mContext.enforceCallingOrSelfPermission(
20864                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20865        final int callingUid = Binder.getCallingUid();
20866        enforceOwnerRights(ownerPackage, callingUid);
20867        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20868        synchronized (mPackages) {
20869            CrossProfileIntentResolver resolver =
20870                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20871            ArraySet<CrossProfileIntentFilter> set =
20872                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
20873            for (CrossProfileIntentFilter filter : set) {
20874                if (filter.getOwnerPackage().equals(ownerPackage)) {
20875                    resolver.removeFilter(filter);
20876                }
20877            }
20878            scheduleWritePackageRestrictionsLocked(sourceUserId);
20879        }
20880    }
20881
20882    // Enforcing that callingUid is owning pkg on userId
20883    private void enforceOwnerRights(String pkg, int callingUid) {
20884        // The system owns everything.
20885        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
20886            return;
20887        }
20888        final int callingUserId = UserHandle.getUserId(callingUid);
20889        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
20890        if (pi == null) {
20891            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
20892                    + callingUserId);
20893        }
20894        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
20895            throw new SecurityException("Calling uid " + callingUid
20896                    + " does not own package " + pkg);
20897        }
20898    }
20899
20900    @Override
20901    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
20902        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20903            return null;
20904        }
20905        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
20906    }
20907
20908    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
20909        UserManagerService ums = UserManagerService.getInstance();
20910        if (ums != null) {
20911            final UserInfo parent = ums.getProfileParent(userId);
20912            final int launcherUid = (parent != null) ? parent.id : userId;
20913            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
20914            if (launcherComponent != null) {
20915                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
20916                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
20917                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
20918                        .setPackage(launcherComponent.getPackageName());
20919                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
20920            }
20921        }
20922    }
20923
20924    /**
20925     * Report the 'Home' activity which is currently set as "always use this one". If non is set
20926     * then reports the most likely home activity or null if there are more than one.
20927     */
20928    private ComponentName getDefaultHomeActivity(int userId) {
20929        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
20930        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
20931        if (cn != null) {
20932            return cn;
20933        }
20934
20935        // Find the launcher with the highest priority and return that component if there are no
20936        // other home activity with the same priority.
20937        int lastPriority = Integer.MIN_VALUE;
20938        ComponentName lastComponent = null;
20939        final int size = allHomeCandidates.size();
20940        for (int i = 0; i < size; i++) {
20941            final ResolveInfo ri = allHomeCandidates.get(i);
20942            if (ri.priority > lastPriority) {
20943                lastComponent = ri.activityInfo.getComponentName();
20944                lastPriority = ri.priority;
20945            } else if (ri.priority == lastPriority) {
20946                // Two components found with same priority.
20947                lastComponent = null;
20948            }
20949        }
20950        return lastComponent;
20951    }
20952
20953    private Intent getHomeIntent() {
20954        Intent intent = new Intent(Intent.ACTION_MAIN);
20955        intent.addCategory(Intent.CATEGORY_HOME);
20956        intent.addCategory(Intent.CATEGORY_DEFAULT);
20957        return intent;
20958    }
20959
20960    private IntentFilter getHomeFilter() {
20961        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
20962        filter.addCategory(Intent.CATEGORY_HOME);
20963        filter.addCategory(Intent.CATEGORY_DEFAULT);
20964        return filter;
20965    }
20966
20967    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
20968            int userId) {
20969        Intent intent  = getHomeIntent();
20970        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
20971                PackageManager.GET_META_DATA, userId);
20972        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
20973                true, false, false, userId);
20974
20975        allHomeCandidates.clear();
20976        if (list != null) {
20977            for (ResolveInfo ri : list) {
20978                allHomeCandidates.add(ri);
20979            }
20980        }
20981        return (preferred == null || preferred.activityInfo == null)
20982                ? null
20983                : new ComponentName(preferred.activityInfo.packageName,
20984                        preferred.activityInfo.name);
20985    }
20986
20987    @Override
20988    public void setHomeActivity(ComponentName comp, int userId) {
20989        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20990            return;
20991        }
20992        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
20993        getHomeActivitiesAsUser(homeActivities, userId);
20994
20995        boolean found = false;
20996
20997        final int size = homeActivities.size();
20998        final ComponentName[] set = new ComponentName[size];
20999        for (int i = 0; i < size; i++) {
21000            final ResolveInfo candidate = homeActivities.get(i);
21001            final ActivityInfo info = candidate.activityInfo;
21002            final ComponentName activityName = new ComponentName(info.packageName, info.name);
21003            set[i] = activityName;
21004            if (!found && activityName.equals(comp)) {
21005                found = true;
21006            }
21007        }
21008        if (!found) {
21009            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
21010                    + userId);
21011        }
21012        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
21013                set, comp, userId);
21014    }
21015
21016    private @Nullable String getSetupWizardPackageName() {
21017        final Intent intent = new Intent(Intent.ACTION_MAIN);
21018        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
21019
21020        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21021                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21022                        | MATCH_DISABLED_COMPONENTS,
21023                UserHandle.myUserId());
21024        if (matches.size() == 1) {
21025            return matches.get(0).getComponentInfo().packageName;
21026        } else {
21027            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
21028                    + ": matches=" + matches);
21029            return null;
21030        }
21031    }
21032
21033    private @Nullable String getStorageManagerPackageName() {
21034        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
21035
21036        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21037                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21038                        | MATCH_DISABLED_COMPONENTS,
21039                UserHandle.myUserId());
21040        if (matches.size() == 1) {
21041            return matches.get(0).getComponentInfo().packageName;
21042        } else {
21043            Slog.e(TAG, "There should probably be exactly one storage manager; found "
21044                    + matches.size() + ": matches=" + matches);
21045            return null;
21046        }
21047    }
21048
21049    @Override
21050    public void setApplicationEnabledSetting(String appPackageName,
21051            int newState, int flags, int userId, String callingPackage) {
21052        if (!sUserManager.exists(userId)) return;
21053        if (callingPackage == null) {
21054            callingPackage = Integer.toString(Binder.getCallingUid());
21055        }
21056        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
21057    }
21058
21059    @Override
21060    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
21061        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
21062        synchronized (mPackages) {
21063            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
21064            if (pkgSetting != null) {
21065                pkgSetting.setUpdateAvailable(updateAvailable);
21066            }
21067        }
21068    }
21069
21070    @Override
21071    public void setComponentEnabledSetting(ComponentName componentName,
21072            int newState, int flags, int userId) {
21073        if (!sUserManager.exists(userId)) return;
21074        setEnabledSetting(componentName.getPackageName(),
21075                componentName.getClassName(), newState, flags, userId, null);
21076    }
21077
21078    private void setEnabledSetting(final String packageName, String className, int newState,
21079            final int flags, int userId, String callingPackage) {
21080        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
21081              || newState == COMPONENT_ENABLED_STATE_ENABLED
21082              || newState == COMPONENT_ENABLED_STATE_DISABLED
21083              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21084              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
21085            throw new IllegalArgumentException("Invalid new component state: "
21086                    + newState);
21087        }
21088        PackageSetting pkgSetting;
21089        final int callingUid = Binder.getCallingUid();
21090        final int permission;
21091        if (callingUid == Process.SYSTEM_UID) {
21092            permission = PackageManager.PERMISSION_GRANTED;
21093        } else {
21094            permission = mContext.checkCallingOrSelfPermission(
21095                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21096        }
21097        enforceCrossUserPermission(callingUid, userId,
21098                false /* requireFullPermission */, true /* checkShell */, "set enabled");
21099        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21100        boolean sendNow = false;
21101        boolean isApp = (className == null);
21102        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
21103        String componentName = isApp ? packageName : className;
21104        int packageUid = -1;
21105        ArrayList<String> components;
21106
21107        // reader
21108        synchronized (mPackages) {
21109            pkgSetting = mSettings.mPackages.get(packageName);
21110            if (pkgSetting == null) {
21111                if (!isCallerInstantApp) {
21112                    if (className == null) {
21113                        throw new IllegalArgumentException("Unknown package: " + packageName);
21114                    }
21115                    throw new IllegalArgumentException(
21116                            "Unknown component: " + packageName + "/" + className);
21117                } else {
21118                    // throw SecurityException to prevent leaking package information
21119                    throw new SecurityException(
21120                            "Attempt to change component state; "
21121                            + "pid=" + Binder.getCallingPid()
21122                            + ", uid=" + callingUid
21123                            + (className == null
21124                                    ? ", package=" + packageName
21125                                    : ", component=" + packageName + "/" + className));
21126                }
21127            }
21128        }
21129
21130        // Limit who can change which apps
21131        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
21132            // Don't allow apps that don't have permission to modify other apps
21133            if (!allowedByPermission
21134                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
21135                throw new SecurityException(
21136                        "Attempt to change component state; "
21137                        + "pid=" + Binder.getCallingPid()
21138                        + ", uid=" + callingUid
21139                        + (className == null
21140                                ? ", package=" + packageName
21141                                : ", component=" + packageName + "/" + className));
21142            }
21143            // Don't allow changing protected packages.
21144            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
21145                throw new SecurityException("Cannot disable a protected package: " + packageName);
21146            }
21147        }
21148
21149        synchronized (mPackages) {
21150            if (callingUid == Process.SHELL_UID
21151                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
21152                // Shell can only change whole packages between ENABLED and DISABLED_USER states
21153                // unless it is a test package.
21154                int oldState = pkgSetting.getEnabled(userId);
21155                if (className == null
21156                    &&
21157                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
21158                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
21159                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
21160                    &&
21161                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21162                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
21163                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
21164                    // ok
21165                } else {
21166                    throw new SecurityException(
21167                            "Shell cannot change component state for " + packageName + "/"
21168                            + className + " to " + newState);
21169                }
21170            }
21171            if (className == null) {
21172                // We're dealing with an application/package level state change
21173                if (pkgSetting.getEnabled(userId) == newState) {
21174                    // Nothing to do
21175                    return;
21176                }
21177                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
21178                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
21179                    // Don't care about who enables an app.
21180                    callingPackage = null;
21181                }
21182                pkgSetting.setEnabled(newState, userId, callingPackage);
21183                // pkgSetting.pkg.mSetEnabled = newState;
21184            } else {
21185                // We're dealing with a component level state change
21186                // First, verify that this is a valid class name.
21187                PackageParser.Package pkg = pkgSetting.pkg;
21188                if (pkg == null || !pkg.hasComponentClassName(className)) {
21189                    if (pkg != null &&
21190                            pkg.applicationInfo.targetSdkVersion >=
21191                                    Build.VERSION_CODES.JELLY_BEAN) {
21192                        throw new IllegalArgumentException("Component class " + className
21193                                + " does not exist in " + packageName);
21194                    } else {
21195                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
21196                                + className + " does not exist in " + packageName);
21197                    }
21198                }
21199                switch (newState) {
21200                case COMPONENT_ENABLED_STATE_ENABLED:
21201                    if (!pkgSetting.enableComponentLPw(className, userId)) {
21202                        return;
21203                    }
21204                    break;
21205                case COMPONENT_ENABLED_STATE_DISABLED:
21206                    if (!pkgSetting.disableComponentLPw(className, userId)) {
21207                        return;
21208                    }
21209                    break;
21210                case COMPONENT_ENABLED_STATE_DEFAULT:
21211                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
21212                        return;
21213                    }
21214                    break;
21215                default:
21216                    Slog.e(TAG, "Invalid new component state: " + newState);
21217                    return;
21218                }
21219            }
21220            scheduleWritePackageRestrictionsLocked(userId);
21221            updateSequenceNumberLP(pkgSetting, new int[] { userId });
21222            final long callingId = Binder.clearCallingIdentity();
21223            try {
21224                updateInstantAppInstallerLocked(packageName);
21225            } finally {
21226                Binder.restoreCallingIdentity(callingId);
21227            }
21228            components = mPendingBroadcasts.get(userId, packageName);
21229            final boolean newPackage = components == null;
21230            if (newPackage) {
21231                components = new ArrayList<String>();
21232            }
21233            if (!components.contains(componentName)) {
21234                components.add(componentName);
21235            }
21236            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
21237                sendNow = true;
21238                // Purge entry from pending broadcast list if another one exists already
21239                // since we are sending one right away.
21240                mPendingBroadcasts.remove(userId, packageName);
21241            } else {
21242                if (newPackage) {
21243                    mPendingBroadcasts.put(userId, packageName, components);
21244                }
21245                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
21246                    // Schedule a message
21247                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
21248                }
21249            }
21250        }
21251
21252        long callingId = Binder.clearCallingIdentity();
21253        try {
21254            if (sendNow) {
21255                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
21256                sendPackageChangedBroadcast(packageName,
21257                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
21258            }
21259        } finally {
21260            Binder.restoreCallingIdentity(callingId);
21261        }
21262    }
21263
21264    @Override
21265    public void flushPackageRestrictionsAsUser(int userId) {
21266        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21267            return;
21268        }
21269        if (!sUserManager.exists(userId)) {
21270            return;
21271        }
21272        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
21273                false /* checkShell */, "flushPackageRestrictions");
21274        synchronized (mPackages) {
21275            mSettings.writePackageRestrictionsLPr(userId);
21276            mDirtyUsers.remove(userId);
21277            if (mDirtyUsers.isEmpty()) {
21278                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
21279            }
21280        }
21281    }
21282
21283    private void sendPackageChangedBroadcast(String packageName,
21284            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
21285        if (DEBUG_INSTALL)
21286            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
21287                    + componentNames);
21288        Bundle extras = new Bundle(4);
21289        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
21290        String nameList[] = new String[componentNames.size()];
21291        componentNames.toArray(nameList);
21292        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
21293        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
21294        extras.putInt(Intent.EXTRA_UID, packageUid);
21295        // If this is not reporting a change of the overall package, then only send it
21296        // to registered receivers.  We don't want to launch a swath of apps for every
21297        // little component state change.
21298        final int flags = !componentNames.contains(packageName)
21299                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
21300        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
21301                new int[] {UserHandle.getUserId(packageUid)});
21302    }
21303
21304    @Override
21305    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
21306        if (!sUserManager.exists(userId)) return;
21307        final int callingUid = Binder.getCallingUid();
21308        if (getInstantAppPackageName(callingUid) != null) {
21309            return;
21310        }
21311        final int permission = mContext.checkCallingOrSelfPermission(
21312                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21313        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21314        enforceCrossUserPermission(callingUid, userId,
21315                true /* requireFullPermission */, true /* checkShell */, "stop package");
21316        // writer
21317        synchronized (mPackages) {
21318            final PackageSetting ps = mSettings.mPackages.get(packageName);
21319            if (!filterAppAccessLPr(ps, callingUid, userId)
21320                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
21321                            allowedByPermission, callingUid, userId)) {
21322                scheduleWritePackageRestrictionsLocked(userId);
21323            }
21324        }
21325    }
21326
21327    @Override
21328    public String getInstallerPackageName(String packageName) {
21329        final int callingUid = Binder.getCallingUid();
21330        if (getInstantAppPackageName(callingUid) != null) {
21331            return null;
21332        }
21333        // reader
21334        synchronized (mPackages) {
21335            final PackageSetting ps = mSettings.mPackages.get(packageName);
21336            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
21337                return null;
21338            }
21339            return mSettings.getInstallerPackageNameLPr(packageName);
21340        }
21341    }
21342
21343    public boolean isOrphaned(String packageName) {
21344        // reader
21345        synchronized (mPackages) {
21346            return mSettings.isOrphaned(packageName);
21347        }
21348    }
21349
21350    @Override
21351    public int getApplicationEnabledSetting(String packageName, int userId) {
21352        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
21353        int callingUid = Binder.getCallingUid();
21354        enforceCrossUserPermission(callingUid, userId,
21355                false /* requireFullPermission */, false /* checkShell */, "get enabled");
21356        // reader
21357        synchronized (mPackages) {
21358            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
21359                return COMPONENT_ENABLED_STATE_DISABLED;
21360            }
21361            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
21362        }
21363    }
21364
21365    @Override
21366    public int getComponentEnabledSetting(ComponentName component, int userId) {
21367        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
21368        int callingUid = Binder.getCallingUid();
21369        enforceCrossUserPermission(callingUid, userId,
21370                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
21371        synchronized (mPackages) {
21372            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
21373                    component, TYPE_UNKNOWN, userId)) {
21374                return COMPONENT_ENABLED_STATE_DISABLED;
21375            }
21376            return mSettings.getComponentEnabledSettingLPr(component, userId);
21377        }
21378    }
21379
21380    @Override
21381    public void enterSafeMode() {
21382        enforceSystemOrRoot("Only the system can request entering safe mode");
21383
21384        if (!mSystemReady) {
21385            mSafeMode = true;
21386        }
21387    }
21388
21389    @Override
21390    public void systemReady() {
21391        enforceSystemOrRoot("Only the system can claim the system is ready");
21392
21393        mSystemReady = true;
21394        final ContentResolver resolver = mContext.getContentResolver();
21395        ContentObserver co = new ContentObserver(mHandler) {
21396            @Override
21397            public void onChange(boolean selfChange) {
21398                mEphemeralAppsDisabled =
21399                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
21400                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
21401            }
21402        };
21403        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
21404                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
21405                false, co, UserHandle.USER_SYSTEM);
21406        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
21407                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
21408        co.onChange(true);
21409
21410        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
21411        // disabled after already being started.
21412        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
21413                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
21414
21415        // Read the compatibilty setting when the system is ready.
21416        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
21417                mContext.getContentResolver(),
21418                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
21419        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
21420        if (DEBUG_SETTINGS) {
21421            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
21422        }
21423
21424        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
21425
21426        synchronized (mPackages) {
21427            // Verify that all of the preferred activity components actually
21428            // exist.  It is possible for applications to be updated and at
21429            // that point remove a previously declared activity component that
21430            // had been set as a preferred activity.  We try to clean this up
21431            // the next time we encounter that preferred activity, but it is
21432            // possible for the user flow to never be able to return to that
21433            // situation so here we do a sanity check to make sure we haven't
21434            // left any junk around.
21435            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
21436            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21437                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21438                removed.clear();
21439                for (PreferredActivity pa : pir.filterSet()) {
21440                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
21441                        removed.add(pa);
21442                    }
21443                }
21444                if (removed.size() > 0) {
21445                    for (int r=0; r<removed.size(); r++) {
21446                        PreferredActivity pa = removed.get(r);
21447                        Slog.w(TAG, "Removing dangling preferred activity: "
21448                                + pa.mPref.mComponent);
21449                        pir.removeFilter(pa);
21450                    }
21451                    mSettings.writePackageRestrictionsLPr(
21452                            mSettings.mPreferredActivities.keyAt(i));
21453                }
21454            }
21455
21456            for (int userId : UserManagerService.getInstance().getUserIds()) {
21457                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
21458                    grantPermissionsUserIds = ArrayUtils.appendInt(
21459                            grantPermissionsUserIds, userId);
21460                }
21461            }
21462        }
21463        sUserManager.systemReady();
21464
21465        // If we upgraded grant all default permissions before kicking off.
21466        for (int userId : grantPermissionsUserIds) {
21467            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
21468        }
21469
21470        // If we did not grant default permissions, we preload from this the
21471        // default permission exceptions lazily to ensure we don't hit the
21472        // disk on a new user creation.
21473        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
21474            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
21475        }
21476
21477        // Kick off any messages waiting for system ready
21478        if (mPostSystemReadyMessages != null) {
21479            for (Message msg : mPostSystemReadyMessages) {
21480                msg.sendToTarget();
21481            }
21482            mPostSystemReadyMessages = null;
21483        }
21484
21485        // Watch for external volumes that come and go over time
21486        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21487        storage.registerListener(mStorageListener);
21488
21489        mInstallerService.systemReady();
21490        mPackageDexOptimizer.systemReady();
21491
21492        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
21493                StorageManagerInternal.class);
21494        StorageManagerInternal.addExternalStoragePolicy(
21495                new StorageManagerInternal.ExternalStorageMountPolicy() {
21496            @Override
21497            public int getMountMode(int uid, String packageName) {
21498                if (Process.isIsolated(uid)) {
21499                    return Zygote.MOUNT_EXTERNAL_NONE;
21500                }
21501                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
21502                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21503                }
21504                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21505                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21506                }
21507                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21508                    return Zygote.MOUNT_EXTERNAL_READ;
21509                }
21510                return Zygote.MOUNT_EXTERNAL_WRITE;
21511            }
21512
21513            @Override
21514            public boolean hasExternalStorage(int uid, String packageName) {
21515                return true;
21516            }
21517        });
21518
21519        // Now that we're mostly running, clean up stale users and apps
21520        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
21521        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
21522
21523        if (mPrivappPermissionsViolations != null) {
21524            Slog.wtf(TAG,"Signature|privileged permissions not in "
21525                    + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
21526            mPrivappPermissionsViolations = null;
21527        }
21528    }
21529
21530    public void waitForAppDataPrepared() {
21531        if (mPrepareAppDataFuture == null) {
21532            return;
21533        }
21534        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
21535        mPrepareAppDataFuture = null;
21536    }
21537
21538    @Override
21539    public boolean isSafeMode() {
21540        // allow instant applications
21541        return mSafeMode;
21542    }
21543
21544    @Override
21545    public boolean hasSystemUidErrors() {
21546        // allow instant applications
21547        return mHasSystemUidErrors;
21548    }
21549
21550    static String arrayToString(int[] array) {
21551        StringBuffer buf = new StringBuffer(128);
21552        buf.append('[');
21553        if (array != null) {
21554            for (int i=0; i<array.length; i++) {
21555                if (i > 0) buf.append(", ");
21556                buf.append(array[i]);
21557            }
21558        }
21559        buf.append(']');
21560        return buf.toString();
21561    }
21562
21563    static class DumpState {
21564        public static final int DUMP_LIBS = 1 << 0;
21565        public static final int DUMP_FEATURES = 1 << 1;
21566        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
21567        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
21568        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
21569        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
21570        public static final int DUMP_PERMISSIONS = 1 << 6;
21571        public static final int DUMP_PACKAGES = 1 << 7;
21572        public static final int DUMP_SHARED_USERS = 1 << 8;
21573        public static final int DUMP_MESSAGES = 1 << 9;
21574        public static final int DUMP_PROVIDERS = 1 << 10;
21575        public static final int DUMP_VERIFIERS = 1 << 11;
21576        public static final int DUMP_PREFERRED = 1 << 12;
21577        public static final int DUMP_PREFERRED_XML = 1 << 13;
21578        public static final int DUMP_KEYSETS = 1 << 14;
21579        public static final int DUMP_VERSION = 1 << 15;
21580        public static final int DUMP_INSTALLS = 1 << 16;
21581        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
21582        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
21583        public static final int DUMP_FROZEN = 1 << 19;
21584        public static final int DUMP_DEXOPT = 1 << 20;
21585        public static final int DUMP_COMPILER_STATS = 1 << 21;
21586        public static final int DUMP_ENABLED_OVERLAYS = 1 << 22;
21587        public static final int DUMP_CHANGES = 1 << 23;
21588
21589        public static final int OPTION_SHOW_FILTERS = 1 << 0;
21590
21591        private int mTypes;
21592
21593        private int mOptions;
21594
21595        private boolean mTitlePrinted;
21596
21597        private SharedUserSetting mSharedUser;
21598
21599        public boolean isDumping(int type) {
21600            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
21601                return true;
21602            }
21603
21604            return (mTypes & type) != 0;
21605        }
21606
21607        public void setDump(int type) {
21608            mTypes |= type;
21609        }
21610
21611        public boolean isOptionEnabled(int option) {
21612            return (mOptions & option) != 0;
21613        }
21614
21615        public void setOptionEnabled(int option) {
21616            mOptions |= option;
21617        }
21618
21619        public boolean onTitlePrinted() {
21620            final boolean printed = mTitlePrinted;
21621            mTitlePrinted = true;
21622            return printed;
21623        }
21624
21625        public boolean getTitlePrinted() {
21626            return mTitlePrinted;
21627        }
21628
21629        public void setTitlePrinted(boolean enabled) {
21630            mTitlePrinted = enabled;
21631        }
21632
21633        public SharedUserSetting getSharedUser() {
21634            return mSharedUser;
21635        }
21636
21637        public void setSharedUser(SharedUserSetting user) {
21638            mSharedUser = user;
21639        }
21640    }
21641
21642    @Override
21643    public void onShellCommand(FileDescriptor in, FileDescriptor out,
21644            FileDescriptor err, String[] args, ShellCallback callback,
21645            ResultReceiver resultReceiver) {
21646        (new PackageManagerShellCommand(this)).exec(
21647                this, in, out, err, args, callback, resultReceiver);
21648    }
21649
21650    @Override
21651    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
21652        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
21653
21654        DumpState dumpState = new DumpState();
21655        boolean fullPreferred = false;
21656        boolean checkin = false;
21657
21658        String packageName = null;
21659        ArraySet<String> permissionNames = null;
21660
21661        int opti = 0;
21662        while (opti < args.length) {
21663            String opt = args[opti];
21664            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
21665                break;
21666            }
21667            opti++;
21668
21669            if ("-a".equals(opt)) {
21670                // Right now we only know how to print all.
21671            } else if ("-h".equals(opt)) {
21672                pw.println("Package manager dump options:");
21673                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
21674                pw.println("    --checkin: dump for a checkin");
21675                pw.println("    -f: print details of intent filters");
21676                pw.println("    -h: print this help");
21677                pw.println("  cmd may be one of:");
21678                pw.println("    l[ibraries]: list known shared libraries");
21679                pw.println("    f[eatures]: list device features");
21680                pw.println("    k[eysets]: print known keysets");
21681                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
21682                pw.println("    perm[issions]: dump permissions");
21683                pw.println("    permission [name ...]: dump declaration and use of given permission");
21684                pw.println("    pref[erred]: print preferred package settings");
21685                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
21686                pw.println("    prov[iders]: dump content providers");
21687                pw.println("    p[ackages]: dump installed packages");
21688                pw.println("    s[hared-users]: dump shared user IDs");
21689                pw.println("    m[essages]: print collected runtime messages");
21690                pw.println("    v[erifiers]: print package verifier info");
21691                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
21692                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
21693                pw.println("    version: print database version info");
21694                pw.println("    write: write current settings now");
21695                pw.println("    installs: details about install sessions");
21696                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
21697                pw.println("    dexopt: dump dexopt state");
21698                pw.println("    compiler-stats: dump compiler statistics");
21699                pw.println("    enabled-overlays: dump list of enabled overlay packages");
21700                pw.println("    <package.name>: info about given package");
21701                return;
21702            } else if ("--checkin".equals(opt)) {
21703                checkin = true;
21704            } else if ("-f".equals(opt)) {
21705                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21706            } else if ("--proto".equals(opt)) {
21707                dumpProto(fd);
21708                return;
21709            } else {
21710                pw.println("Unknown argument: " + opt + "; use -h for help");
21711            }
21712        }
21713
21714        // Is the caller requesting to dump a particular piece of data?
21715        if (opti < args.length) {
21716            String cmd = args[opti];
21717            opti++;
21718            // Is this a package name?
21719            if ("android".equals(cmd) || cmd.contains(".")) {
21720                packageName = cmd;
21721                // When dumping a single package, we always dump all of its
21722                // filter information since the amount of data will be reasonable.
21723                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21724            } else if ("check-permission".equals(cmd)) {
21725                if (opti >= args.length) {
21726                    pw.println("Error: check-permission missing permission argument");
21727                    return;
21728                }
21729                String perm = args[opti];
21730                opti++;
21731                if (opti >= args.length) {
21732                    pw.println("Error: check-permission missing package argument");
21733                    return;
21734                }
21735
21736                String pkg = args[opti];
21737                opti++;
21738                int user = UserHandle.getUserId(Binder.getCallingUid());
21739                if (opti < args.length) {
21740                    try {
21741                        user = Integer.parseInt(args[opti]);
21742                    } catch (NumberFormatException e) {
21743                        pw.println("Error: check-permission user argument is not a number: "
21744                                + args[opti]);
21745                        return;
21746                    }
21747                }
21748
21749                // Normalize package name to handle renamed packages and static libs
21750                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
21751
21752                pw.println(checkPermission(perm, pkg, user));
21753                return;
21754            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
21755                dumpState.setDump(DumpState.DUMP_LIBS);
21756            } else if ("f".equals(cmd) || "features".equals(cmd)) {
21757                dumpState.setDump(DumpState.DUMP_FEATURES);
21758            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
21759                if (opti >= args.length) {
21760                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
21761                            | DumpState.DUMP_SERVICE_RESOLVERS
21762                            | DumpState.DUMP_RECEIVER_RESOLVERS
21763                            | DumpState.DUMP_CONTENT_RESOLVERS);
21764                } else {
21765                    while (opti < args.length) {
21766                        String name = args[opti];
21767                        if ("a".equals(name) || "activity".equals(name)) {
21768                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
21769                        } else if ("s".equals(name) || "service".equals(name)) {
21770                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
21771                        } else if ("r".equals(name) || "receiver".equals(name)) {
21772                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
21773                        } else if ("c".equals(name) || "content".equals(name)) {
21774                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
21775                        } else {
21776                            pw.println("Error: unknown resolver table type: " + name);
21777                            return;
21778                        }
21779                        opti++;
21780                    }
21781                }
21782            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
21783                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
21784            } else if ("permission".equals(cmd)) {
21785                if (opti >= args.length) {
21786                    pw.println("Error: permission requires permission name");
21787                    return;
21788                }
21789                permissionNames = new ArraySet<>();
21790                while (opti < args.length) {
21791                    permissionNames.add(args[opti]);
21792                    opti++;
21793                }
21794                dumpState.setDump(DumpState.DUMP_PERMISSIONS
21795                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
21796            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
21797                dumpState.setDump(DumpState.DUMP_PREFERRED);
21798            } else if ("preferred-xml".equals(cmd)) {
21799                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
21800                if (opti < args.length && "--full".equals(args[opti])) {
21801                    fullPreferred = true;
21802                    opti++;
21803                }
21804            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
21805                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
21806            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
21807                dumpState.setDump(DumpState.DUMP_PACKAGES);
21808            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
21809                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
21810            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
21811                dumpState.setDump(DumpState.DUMP_PROVIDERS);
21812            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
21813                dumpState.setDump(DumpState.DUMP_MESSAGES);
21814            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
21815                dumpState.setDump(DumpState.DUMP_VERIFIERS);
21816            } else if ("i".equals(cmd) || "ifv".equals(cmd)
21817                    || "intent-filter-verifiers".equals(cmd)) {
21818                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
21819            } else if ("version".equals(cmd)) {
21820                dumpState.setDump(DumpState.DUMP_VERSION);
21821            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
21822                dumpState.setDump(DumpState.DUMP_KEYSETS);
21823            } else if ("installs".equals(cmd)) {
21824                dumpState.setDump(DumpState.DUMP_INSTALLS);
21825            } else if ("frozen".equals(cmd)) {
21826                dumpState.setDump(DumpState.DUMP_FROZEN);
21827            } else if ("dexopt".equals(cmd)) {
21828                dumpState.setDump(DumpState.DUMP_DEXOPT);
21829            } else if ("compiler-stats".equals(cmd)) {
21830                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
21831            } else if ("enabled-overlays".equals(cmd)) {
21832                dumpState.setDump(DumpState.DUMP_ENABLED_OVERLAYS);
21833            } else if ("changes".equals(cmd)) {
21834                dumpState.setDump(DumpState.DUMP_CHANGES);
21835            } else if ("write".equals(cmd)) {
21836                synchronized (mPackages) {
21837                    mSettings.writeLPr();
21838                    pw.println("Settings written.");
21839                    return;
21840                }
21841            }
21842        }
21843
21844        if (checkin) {
21845            pw.println("vers,1");
21846        }
21847
21848        // reader
21849        synchronized (mPackages) {
21850            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
21851                if (!checkin) {
21852                    if (dumpState.onTitlePrinted())
21853                        pw.println();
21854                    pw.println("Database versions:");
21855                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
21856                }
21857            }
21858
21859            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
21860                if (!checkin) {
21861                    if (dumpState.onTitlePrinted())
21862                        pw.println();
21863                    pw.println("Verifiers:");
21864                    pw.print("  Required: ");
21865                    pw.print(mRequiredVerifierPackage);
21866                    pw.print(" (uid=");
21867                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21868                            UserHandle.USER_SYSTEM));
21869                    pw.println(")");
21870                } else if (mRequiredVerifierPackage != null) {
21871                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
21872                    pw.print(",");
21873                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21874                            UserHandle.USER_SYSTEM));
21875                }
21876            }
21877
21878            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
21879                    packageName == null) {
21880                if (mIntentFilterVerifierComponent != null) {
21881                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21882                    if (!checkin) {
21883                        if (dumpState.onTitlePrinted())
21884                            pw.println();
21885                        pw.println("Intent Filter Verifier:");
21886                        pw.print("  Using: ");
21887                        pw.print(verifierPackageName);
21888                        pw.print(" (uid=");
21889                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21890                                UserHandle.USER_SYSTEM));
21891                        pw.println(")");
21892                    } else if (verifierPackageName != null) {
21893                        pw.print("ifv,"); pw.print(verifierPackageName);
21894                        pw.print(",");
21895                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21896                                UserHandle.USER_SYSTEM));
21897                    }
21898                } else {
21899                    pw.println();
21900                    pw.println("No Intent Filter Verifier available!");
21901                }
21902            }
21903
21904            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
21905                boolean printedHeader = false;
21906                final Iterator<String> it = mSharedLibraries.keySet().iterator();
21907                while (it.hasNext()) {
21908                    String libName = it.next();
21909                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
21910                    if (versionedLib == null) {
21911                        continue;
21912                    }
21913                    final int versionCount = versionedLib.size();
21914                    for (int i = 0; i < versionCount; i++) {
21915                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
21916                        if (!checkin) {
21917                            if (!printedHeader) {
21918                                if (dumpState.onTitlePrinted())
21919                                    pw.println();
21920                                pw.println("Libraries:");
21921                                printedHeader = true;
21922                            }
21923                            pw.print("  ");
21924                        } else {
21925                            pw.print("lib,");
21926                        }
21927                        pw.print(libEntry.info.getName());
21928                        if (libEntry.info.isStatic()) {
21929                            pw.print(" version=" + libEntry.info.getVersion());
21930                        }
21931                        if (!checkin) {
21932                            pw.print(" -> ");
21933                        }
21934                        if (libEntry.path != null) {
21935                            pw.print(" (jar) ");
21936                            pw.print(libEntry.path);
21937                        } else {
21938                            pw.print(" (apk) ");
21939                            pw.print(libEntry.apk);
21940                        }
21941                        pw.println();
21942                    }
21943                }
21944            }
21945
21946            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
21947                if (dumpState.onTitlePrinted())
21948                    pw.println();
21949                if (!checkin) {
21950                    pw.println("Features:");
21951                }
21952
21953                synchronized (mAvailableFeatures) {
21954                    for (FeatureInfo feat : mAvailableFeatures.values()) {
21955                        if (checkin) {
21956                            pw.print("feat,");
21957                            pw.print(feat.name);
21958                            pw.print(",");
21959                            pw.println(feat.version);
21960                        } else {
21961                            pw.print("  ");
21962                            pw.print(feat.name);
21963                            if (feat.version > 0) {
21964                                pw.print(" version=");
21965                                pw.print(feat.version);
21966                            }
21967                            pw.println();
21968                        }
21969                    }
21970                }
21971            }
21972
21973            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
21974                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
21975                        : "Activity Resolver Table:", "  ", packageName,
21976                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21977                    dumpState.setTitlePrinted(true);
21978                }
21979            }
21980            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
21981                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
21982                        : "Receiver Resolver Table:", "  ", packageName,
21983                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21984                    dumpState.setTitlePrinted(true);
21985                }
21986            }
21987            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
21988                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
21989                        : "Service Resolver Table:", "  ", packageName,
21990                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21991                    dumpState.setTitlePrinted(true);
21992                }
21993            }
21994            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
21995                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
21996                        : "Provider Resolver Table:", "  ", packageName,
21997                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21998                    dumpState.setTitlePrinted(true);
21999                }
22000            }
22001
22002            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
22003                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
22004                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
22005                    int user = mSettings.mPreferredActivities.keyAt(i);
22006                    if (pir.dump(pw,
22007                            dumpState.getTitlePrinted()
22008                                ? "\nPreferred Activities User " + user + ":"
22009                                : "Preferred Activities User " + user + ":", "  ",
22010                            packageName, true, false)) {
22011                        dumpState.setTitlePrinted(true);
22012                    }
22013                }
22014            }
22015
22016            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
22017                pw.flush();
22018                FileOutputStream fout = new FileOutputStream(fd);
22019                BufferedOutputStream str = new BufferedOutputStream(fout);
22020                XmlSerializer serializer = new FastXmlSerializer();
22021                try {
22022                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
22023                    serializer.startDocument(null, true);
22024                    serializer.setFeature(
22025                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
22026                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
22027                    serializer.endDocument();
22028                    serializer.flush();
22029                } catch (IllegalArgumentException e) {
22030                    pw.println("Failed writing: " + e);
22031                } catch (IllegalStateException e) {
22032                    pw.println("Failed writing: " + e);
22033                } catch (IOException e) {
22034                    pw.println("Failed writing: " + e);
22035                }
22036            }
22037
22038            if (!checkin
22039                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
22040                    && packageName == null) {
22041                pw.println();
22042                int count = mSettings.mPackages.size();
22043                if (count == 0) {
22044                    pw.println("No applications!");
22045                    pw.println();
22046                } else {
22047                    final String prefix = "  ";
22048                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
22049                    if (allPackageSettings.size() == 0) {
22050                        pw.println("No domain preferred apps!");
22051                        pw.println();
22052                    } else {
22053                        pw.println("App verification status:");
22054                        pw.println();
22055                        count = 0;
22056                        for (PackageSetting ps : allPackageSettings) {
22057                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
22058                            if (ivi == null || ivi.getPackageName() == null) continue;
22059                            pw.println(prefix + "Package: " + ivi.getPackageName());
22060                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
22061                            pw.println(prefix + "Status:  " + ivi.getStatusString());
22062                            pw.println();
22063                            count++;
22064                        }
22065                        if (count == 0) {
22066                            pw.println(prefix + "No app verification established.");
22067                            pw.println();
22068                        }
22069                        for (int userId : sUserManager.getUserIds()) {
22070                            pw.println("App linkages for user " + userId + ":");
22071                            pw.println();
22072                            count = 0;
22073                            for (PackageSetting ps : allPackageSettings) {
22074                                final long status = ps.getDomainVerificationStatusForUser(userId);
22075                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
22076                                        && !DEBUG_DOMAIN_VERIFICATION) {
22077                                    continue;
22078                                }
22079                                pw.println(prefix + "Package: " + ps.name);
22080                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
22081                                String statusStr = IntentFilterVerificationInfo.
22082                                        getStatusStringFromValue(status);
22083                                pw.println(prefix + "Status:  " + statusStr);
22084                                pw.println();
22085                                count++;
22086                            }
22087                            if (count == 0) {
22088                                pw.println(prefix + "No configured app linkages.");
22089                                pw.println();
22090                            }
22091                        }
22092                    }
22093                }
22094            }
22095
22096            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
22097                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
22098                if (packageName == null && permissionNames == null) {
22099                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
22100                        if (iperm == 0) {
22101                            if (dumpState.onTitlePrinted())
22102                                pw.println();
22103                            pw.println("AppOp Permissions:");
22104                        }
22105                        pw.print("  AppOp Permission ");
22106                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
22107                        pw.println(":");
22108                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
22109                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
22110                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
22111                        }
22112                    }
22113                }
22114            }
22115
22116            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
22117                boolean printedSomething = false;
22118                for (PackageParser.Provider p : mProviders.mProviders.values()) {
22119                    if (packageName != null && !packageName.equals(p.info.packageName)) {
22120                        continue;
22121                    }
22122                    if (!printedSomething) {
22123                        if (dumpState.onTitlePrinted())
22124                            pw.println();
22125                        pw.println("Registered ContentProviders:");
22126                        printedSomething = true;
22127                    }
22128                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
22129                    pw.print("    "); pw.println(p.toString());
22130                }
22131                printedSomething = false;
22132                for (Map.Entry<String, PackageParser.Provider> entry :
22133                        mProvidersByAuthority.entrySet()) {
22134                    PackageParser.Provider p = entry.getValue();
22135                    if (packageName != null && !packageName.equals(p.info.packageName)) {
22136                        continue;
22137                    }
22138                    if (!printedSomething) {
22139                        if (dumpState.onTitlePrinted())
22140                            pw.println();
22141                        pw.println("ContentProvider Authorities:");
22142                        printedSomething = true;
22143                    }
22144                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
22145                    pw.print("    "); pw.println(p.toString());
22146                    if (p.info != null && p.info.applicationInfo != null) {
22147                        final String appInfo = p.info.applicationInfo.toString();
22148                        pw.print("      applicationInfo="); pw.println(appInfo);
22149                    }
22150                }
22151            }
22152
22153            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
22154                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
22155            }
22156
22157            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
22158                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
22159            }
22160
22161            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
22162                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
22163            }
22164
22165            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
22166                if (dumpState.onTitlePrinted()) pw.println();
22167                pw.println("Package Changes:");
22168                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
22169                final int K = mChangedPackages.size();
22170                for (int i = 0; i < K; i++) {
22171                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
22172                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
22173                    final int N = changes.size();
22174                    if (N == 0) {
22175                        pw.print("    "); pw.println("No packages changed");
22176                    } else {
22177                        for (int j = 0; j < N; j++) {
22178                            final String pkgName = changes.valueAt(j);
22179                            final int sequenceNumber = changes.keyAt(j);
22180                            pw.print("    ");
22181                            pw.print("seq=");
22182                            pw.print(sequenceNumber);
22183                            pw.print(", package=");
22184                            pw.println(pkgName);
22185                        }
22186                    }
22187                }
22188            }
22189
22190            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
22191                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
22192            }
22193
22194            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
22195                // XXX should handle packageName != null by dumping only install data that
22196                // the given package is involved with.
22197                if (dumpState.onTitlePrinted()) pw.println();
22198
22199                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22200                ipw.println();
22201                ipw.println("Frozen packages:");
22202                ipw.increaseIndent();
22203                if (mFrozenPackages.size() == 0) {
22204                    ipw.println("(none)");
22205                } else {
22206                    for (int i = 0; i < mFrozenPackages.size(); i++) {
22207                        ipw.println(mFrozenPackages.valueAt(i));
22208                    }
22209                }
22210                ipw.decreaseIndent();
22211            }
22212
22213            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
22214                if (dumpState.onTitlePrinted()) pw.println();
22215                dumpDexoptStateLPr(pw, packageName);
22216            }
22217
22218            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
22219                if (dumpState.onTitlePrinted()) pw.println();
22220                dumpCompilerStatsLPr(pw, packageName);
22221            }
22222
22223            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
22224                if (dumpState.onTitlePrinted()) pw.println();
22225                mSettings.dumpReadMessagesLPr(pw, dumpState);
22226
22227                pw.println();
22228                pw.println("Package warning messages:");
22229                BufferedReader in = null;
22230                String line = null;
22231                try {
22232                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22233                    while ((line = in.readLine()) != null) {
22234                        if (line.contains("ignored: updated version")) continue;
22235                        pw.println(line);
22236                    }
22237                } catch (IOException ignored) {
22238                } finally {
22239                    IoUtils.closeQuietly(in);
22240                }
22241            }
22242
22243            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
22244                BufferedReader in = null;
22245                String line = null;
22246                try {
22247                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22248                    while ((line = in.readLine()) != null) {
22249                        if (line.contains("ignored: updated version")) continue;
22250                        pw.print("msg,");
22251                        pw.println(line);
22252                    }
22253                } catch (IOException ignored) {
22254                } finally {
22255                    IoUtils.closeQuietly(in);
22256                }
22257            }
22258        }
22259
22260        // PackageInstaller should be called outside of mPackages lock
22261        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
22262            // XXX should handle packageName != null by dumping only install data that
22263            // the given package is involved with.
22264            if (dumpState.onTitlePrinted()) pw.println();
22265            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
22266        }
22267    }
22268
22269    private void dumpProto(FileDescriptor fd) {
22270        final ProtoOutputStream proto = new ProtoOutputStream(fd);
22271
22272        synchronized (mPackages) {
22273            final long requiredVerifierPackageToken =
22274                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
22275            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
22276            proto.write(
22277                    PackageServiceDumpProto.PackageShortProto.UID,
22278                    getPackageUid(
22279                            mRequiredVerifierPackage,
22280                            MATCH_DEBUG_TRIAGED_MISSING,
22281                            UserHandle.USER_SYSTEM));
22282            proto.end(requiredVerifierPackageToken);
22283
22284            if (mIntentFilterVerifierComponent != null) {
22285                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
22286                final long verifierPackageToken =
22287                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
22288                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
22289                proto.write(
22290                        PackageServiceDumpProto.PackageShortProto.UID,
22291                        getPackageUid(
22292                                verifierPackageName,
22293                                MATCH_DEBUG_TRIAGED_MISSING,
22294                                UserHandle.USER_SYSTEM));
22295                proto.end(verifierPackageToken);
22296            }
22297
22298            dumpSharedLibrariesProto(proto);
22299            dumpFeaturesProto(proto);
22300            mSettings.dumpPackagesProto(proto);
22301            mSettings.dumpSharedUsersProto(proto);
22302            dumpMessagesProto(proto);
22303        }
22304        proto.flush();
22305    }
22306
22307    private void dumpMessagesProto(ProtoOutputStream proto) {
22308        BufferedReader in = null;
22309        String line = null;
22310        try {
22311            in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22312            while ((line = in.readLine()) != null) {
22313                if (line.contains("ignored: updated version")) continue;
22314                proto.write(PackageServiceDumpProto.MESSAGES, line);
22315            }
22316        } catch (IOException ignored) {
22317        } finally {
22318            IoUtils.closeQuietly(in);
22319        }
22320    }
22321
22322    private void dumpFeaturesProto(ProtoOutputStream proto) {
22323        synchronized (mAvailableFeatures) {
22324            final int count = mAvailableFeatures.size();
22325            for (int i = 0; i < count; i++) {
22326                final FeatureInfo feat = mAvailableFeatures.valueAt(i);
22327                final long featureToken = proto.start(PackageServiceDumpProto.FEATURES);
22328                proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name);
22329                proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version);
22330                proto.end(featureToken);
22331            }
22332        }
22333    }
22334
22335    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
22336        final int count = mSharedLibraries.size();
22337        for (int i = 0; i < count; i++) {
22338            final String libName = mSharedLibraries.keyAt(i);
22339            SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
22340            if (versionedLib == null) {
22341                continue;
22342            }
22343            final int versionCount = versionedLib.size();
22344            for (int j = 0; j < versionCount; j++) {
22345                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
22346                final long sharedLibraryToken =
22347                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
22348                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
22349                final boolean isJar = (libEntry.path != null);
22350                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
22351                if (isJar) {
22352                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
22353                } else {
22354                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
22355                }
22356                proto.end(sharedLibraryToken);
22357            }
22358        }
22359    }
22360
22361    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
22362        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22363        ipw.println();
22364        ipw.println("Dexopt state:");
22365        ipw.increaseIndent();
22366        Collection<PackageParser.Package> packages = null;
22367        if (packageName != null) {
22368            PackageParser.Package targetPackage = mPackages.get(packageName);
22369            if (targetPackage != null) {
22370                packages = Collections.singletonList(targetPackage);
22371            } else {
22372                ipw.println("Unable to find package: " + packageName);
22373                return;
22374            }
22375        } else {
22376            packages = mPackages.values();
22377        }
22378
22379        for (PackageParser.Package pkg : packages) {
22380            ipw.println("[" + pkg.packageName + "]");
22381            ipw.increaseIndent();
22382            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
22383            ipw.decreaseIndent();
22384        }
22385    }
22386
22387    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
22388        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22389        ipw.println();
22390        ipw.println("Compiler stats:");
22391        ipw.increaseIndent();
22392        Collection<PackageParser.Package> packages = null;
22393        if (packageName != null) {
22394            PackageParser.Package targetPackage = mPackages.get(packageName);
22395            if (targetPackage != null) {
22396                packages = Collections.singletonList(targetPackage);
22397            } else {
22398                ipw.println("Unable to find package: " + packageName);
22399                return;
22400            }
22401        } else {
22402            packages = mPackages.values();
22403        }
22404
22405        for (PackageParser.Package pkg : packages) {
22406            ipw.println("[" + pkg.packageName + "]");
22407            ipw.increaseIndent();
22408
22409            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
22410            if (stats == null) {
22411                ipw.println("(No recorded stats)");
22412            } else {
22413                stats.dump(ipw);
22414            }
22415            ipw.decreaseIndent();
22416        }
22417    }
22418
22419    private String dumpDomainString(String packageName) {
22420        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
22421                .getList();
22422        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
22423
22424        ArraySet<String> result = new ArraySet<>();
22425        if (iviList.size() > 0) {
22426            for (IntentFilterVerificationInfo ivi : iviList) {
22427                for (String host : ivi.getDomains()) {
22428                    result.add(host);
22429                }
22430            }
22431        }
22432        if (filters != null && filters.size() > 0) {
22433            for (IntentFilter filter : filters) {
22434                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
22435                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
22436                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
22437                    result.addAll(filter.getHostsList());
22438                }
22439            }
22440        }
22441
22442        StringBuilder sb = new StringBuilder(result.size() * 16);
22443        for (String domain : result) {
22444            if (sb.length() > 0) sb.append(" ");
22445            sb.append(domain);
22446        }
22447        return sb.toString();
22448    }
22449
22450    // ------- apps on sdcard specific code -------
22451    static final boolean DEBUG_SD_INSTALL = false;
22452
22453    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
22454
22455    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
22456
22457    private boolean mMediaMounted = false;
22458
22459    static String getEncryptKey() {
22460        try {
22461            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
22462                    SD_ENCRYPTION_KEYSTORE_NAME);
22463            if (sdEncKey == null) {
22464                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
22465                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
22466                if (sdEncKey == null) {
22467                    Slog.e(TAG, "Failed to create encryption keys");
22468                    return null;
22469                }
22470            }
22471            return sdEncKey;
22472        } catch (NoSuchAlgorithmException nsae) {
22473            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
22474            return null;
22475        } catch (IOException ioe) {
22476            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
22477            return null;
22478        }
22479    }
22480
22481    /*
22482     * Update media status on PackageManager.
22483     */
22484    @Override
22485    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
22486        enforceSystemOrRoot("Media status can only be updated by the system");
22487        // reader; this apparently protects mMediaMounted, but should probably
22488        // be a different lock in that case.
22489        synchronized (mPackages) {
22490            Log.i(TAG, "Updating external media status from "
22491                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
22492                    + (mediaStatus ? "mounted" : "unmounted"));
22493            if (DEBUG_SD_INSTALL)
22494                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
22495                        + ", mMediaMounted=" + mMediaMounted);
22496            if (mediaStatus == mMediaMounted) {
22497                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
22498                        : 0, -1);
22499                mHandler.sendMessage(msg);
22500                return;
22501            }
22502            mMediaMounted = mediaStatus;
22503        }
22504        // Queue up an async operation since the package installation may take a
22505        // little while.
22506        mHandler.post(new Runnable() {
22507            public void run() {
22508                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
22509            }
22510        });
22511    }
22512
22513    /**
22514     * Called by StorageManagerService when the initial ASECs to scan are available.
22515     * Should block until all the ASEC containers are finished being scanned.
22516     */
22517    public void scanAvailableAsecs() {
22518        updateExternalMediaStatusInner(true, false, false);
22519    }
22520
22521    /*
22522     * Collect information of applications on external media, map them against
22523     * existing containers and update information based on current mount status.
22524     * Please note that we always have to report status if reportStatus has been
22525     * set to true especially when unloading packages.
22526     */
22527    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
22528            boolean externalStorage) {
22529        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
22530        int[] uidArr = EmptyArray.INT;
22531
22532        final String[] list = PackageHelper.getSecureContainerList();
22533        if (ArrayUtils.isEmpty(list)) {
22534            Log.i(TAG, "No secure containers found");
22535        } else {
22536            // Process list of secure containers and categorize them
22537            // as active or stale based on their package internal state.
22538
22539            // reader
22540            synchronized (mPackages) {
22541                for (String cid : list) {
22542                    // Leave stages untouched for now; installer service owns them
22543                    if (PackageInstallerService.isStageName(cid)) continue;
22544
22545                    if (DEBUG_SD_INSTALL)
22546                        Log.i(TAG, "Processing container " + cid);
22547                    String pkgName = getAsecPackageName(cid);
22548                    if (pkgName == null) {
22549                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
22550                        continue;
22551                    }
22552                    if (DEBUG_SD_INSTALL)
22553                        Log.i(TAG, "Looking for pkg : " + pkgName);
22554
22555                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
22556                    if (ps == null) {
22557                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
22558                        continue;
22559                    }
22560
22561                    /*
22562                     * Skip packages that are not external if we're unmounting
22563                     * external storage.
22564                     */
22565                    if (externalStorage && !isMounted && !isExternal(ps)) {
22566                        continue;
22567                    }
22568
22569                    final AsecInstallArgs args = new AsecInstallArgs(cid,
22570                            getAppDexInstructionSets(ps), ps.isForwardLocked());
22571                    // The package status is changed only if the code path
22572                    // matches between settings and the container id.
22573                    if (ps.codePathString != null
22574                            && ps.codePathString.startsWith(args.getCodePath())) {
22575                        if (DEBUG_SD_INSTALL) {
22576                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
22577                                    + " at code path: " + ps.codePathString);
22578                        }
22579
22580                        // We do have a valid package installed on sdcard
22581                        processCids.put(args, ps.codePathString);
22582                        final int uid = ps.appId;
22583                        if (uid != -1) {
22584                            uidArr = ArrayUtils.appendInt(uidArr, uid);
22585                        }
22586                    } else {
22587                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
22588                                + ps.codePathString);
22589                    }
22590                }
22591            }
22592
22593            Arrays.sort(uidArr);
22594        }
22595
22596        // Process packages with valid entries.
22597        if (isMounted) {
22598            if (DEBUG_SD_INSTALL)
22599                Log.i(TAG, "Loading packages");
22600            loadMediaPackages(processCids, uidArr, externalStorage);
22601            startCleaningPackages();
22602            mInstallerService.onSecureContainersAvailable();
22603        } else {
22604            if (DEBUG_SD_INSTALL)
22605                Log.i(TAG, "Unloading packages");
22606            unloadMediaPackages(processCids, uidArr, reportStatus);
22607        }
22608    }
22609
22610    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22611            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
22612        final int size = infos.size();
22613        final String[] packageNames = new String[size];
22614        final int[] packageUids = new int[size];
22615        for (int i = 0; i < size; i++) {
22616            final ApplicationInfo info = infos.get(i);
22617            packageNames[i] = info.packageName;
22618            packageUids[i] = info.uid;
22619        }
22620        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
22621                finishedReceiver);
22622    }
22623
22624    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22625            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
22626        sendResourcesChangedBroadcast(mediaStatus, replacing,
22627                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
22628    }
22629
22630    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22631            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
22632        int size = pkgList.length;
22633        if (size > 0) {
22634            // Send broadcasts here
22635            Bundle extras = new Bundle();
22636            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
22637            if (uidArr != null) {
22638                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
22639            }
22640            if (replacing) {
22641                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
22642            }
22643            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
22644                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
22645            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
22646        }
22647    }
22648
22649   /*
22650     * Look at potentially valid container ids from processCids If package
22651     * information doesn't match the one on record or package scanning fails,
22652     * the cid is added to list of removeCids. We currently don't delete stale
22653     * containers.
22654     */
22655    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
22656            boolean externalStorage) {
22657        ArrayList<String> pkgList = new ArrayList<String>();
22658        Set<AsecInstallArgs> keys = processCids.keySet();
22659
22660        for (AsecInstallArgs args : keys) {
22661            String codePath = processCids.get(args);
22662            if (DEBUG_SD_INSTALL)
22663                Log.i(TAG, "Loading container : " + args.cid);
22664            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
22665            try {
22666                // Make sure there are no container errors first.
22667                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
22668                    Slog.e(TAG, "Failed to mount cid : " + args.cid
22669                            + " when installing from sdcard");
22670                    continue;
22671                }
22672                // Check code path here.
22673                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
22674                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
22675                            + " does not match one in settings " + codePath);
22676                    continue;
22677                }
22678                // Parse package
22679                int parseFlags = mDefParseFlags;
22680                if (args.isExternalAsec()) {
22681                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
22682                }
22683                if (args.isFwdLocked()) {
22684                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
22685                }
22686
22687                synchronized (mInstallLock) {
22688                    PackageParser.Package pkg = null;
22689                    try {
22690                        // Sadly we don't know the package name yet to freeze it
22691                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
22692                                SCAN_IGNORE_FROZEN, 0, null);
22693                    } catch (PackageManagerException e) {
22694                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
22695                    }
22696                    // Scan the package
22697                    if (pkg != null) {
22698                        /*
22699                         * TODO why is the lock being held? doPostInstall is
22700                         * called in other places without the lock. This needs
22701                         * to be straightened out.
22702                         */
22703                        // writer
22704                        synchronized (mPackages) {
22705                            retCode = PackageManager.INSTALL_SUCCEEDED;
22706                            pkgList.add(pkg.packageName);
22707                            // Post process args
22708                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
22709                                    pkg.applicationInfo.uid);
22710                        }
22711                    } else {
22712                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
22713                    }
22714                }
22715
22716            } finally {
22717                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
22718                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
22719                }
22720            }
22721        }
22722        // writer
22723        synchronized (mPackages) {
22724            // If the platform SDK has changed since the last time we booted,
22725            // we need to re-grant app permission to catch any new ones that
22726            // appear. This is really a hack, and means that apps can in some
22727            // cases get permissions that the user didn't initially explicitly
22728            // allow... it would be nice to have some better way to handle
22729            // this situation.
22730            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
22731                    : mSettings.getInternalVersion();
22732            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
22733                    : StorageManager.UUID_PRIVATE_INTERNAL;
22734
22735            int updateFlags = UPDATE_PERMISSIONS_ALL;
22736            if (ver.sdkVersion != mSdkVersion) {
22737                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
22738                        + mSdkVersion + "; regranting permissions for external");
22739                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
22740            }
22741            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
22742
22743            // Yay, everything is now upgraded
22744            ver.forceCurrent();
22745
22746            // can downgrade to reader
22747            // Persist settings
22748            mSettings.writeLPr();
22749        }
22750        // Send a broadcast to let everyone know we are done processing
22751        if (pkgList.size() > 0) {
22752            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
22753        }
22754    }
22755
22756   /*
22757     * Utility method to unload a list of specified containers
22758     */
22759    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
22760        // Just unmount all valid containers.
22761        for (AsecInstallArgs arg : cidArgs) {
22762            synchronized (mInstallLock) {
22763                arg.doPostDeleteLI(false);
22764           }
22765       }
22766   }
22767
22768    /*
22769     * Unload packages mounted on external media. This involves deleting package
22770     * data from internal structures, sending broadcasts about disabled packages,
22771     * gc'ing to free up references, unmounting all secure containers
22772     * corresponding to packages on external media, and posting a
22773     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
22774     * that we always have to post this message if status has been requested no
22775     * matter what.
22776     */
22777    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
22778            final boolean reportStatus) {
22779        if (DEBUG_SD_INSTALL)
22780            Log.i(TAG, "unloading media packages");
22781        ArrayList<String> pkgList = new ArrayList<String>();
22782        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
22783        final Set<AsecInstallArgs> keys = processCids.keySet();
22784        for (AsecInstallArgs args : keys) {
22785            String pkgName = args.getPackageName();
22786            if (DEBUG_SD_INSTALL)
22787                Log.i(TAG, "Trying to unload pkg : " + pkgName);
22788            // Delete package internally
22789            PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
22790            synchronized (mInstallLock) {
22791                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
22792                final boolean res;
22793                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
22794                        "unloadMediaPackages")) {
22795                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
22796                            null);
22797                }
22798                if (res) {
22799                    pkgList.add(pkgName);
22800                } else {
22801                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
22802                    failedList.add(args);
22803                }
22804            }
22805        }
22806
22807        // reader
22808        synchronized (mPackages) {
22809            // We didn't update the settings after removing each package;
22810            // write them now for all packages.
22811            mSettings.writeLPr();
22812        }
22813
22814        // We have to absolutely send UPDATED_MEDIA_STATUS only
22815        // after confirming that all the receivers processed the ordered
22816        // broadcast when packages get disabled, force a gc to clean things up.
22817        // and unload all the containers.
22818        if (pkgList.size() > 0) {
22819            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
22820                    new IIntentReceiver.Stub() {
22821                public void performReceive(Intent intent, int resultCode, String data,
22822                        Bundle extras, boolean ordered, boolean sticky,
22823                        int sendingUser) throws RemoteException {
22824                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
22825                            reportStatus ? 1 : 0, 1, keys);
22826                    mHandler.sendMessage(msg);
22827                }
22828            });
22829        } else {
22830            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
22831                    keys);
22832            mHandler.sendMessage(msg);
22833        }
22834    }
22835
22836    private void loadPrivatePackages(final VolumeInfo vol) {
22837        mHandler.post(new Runnable() {
22838            @Override
22839            public void run() {
22840                loadPrivatePackagesInner(vol);
22841            }
22842        });
22843    }
22844
22845    private void loadPrivatePackagesInner(VolumeInfo vol) {
22846        final String volumeUuid = vol.fsUuid;
22847        if (TextUtils.isEmpty(volumeUuid)) {
22848            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
22849            return;
22850        }
22851
22852        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
22853        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
22854        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
22855
22856        final VersionInfo ver;
22857        final List<PackageSetting> packages;
22858        synchronized (mPackages) {
22859            ver = mSettings.findOrCreateVersion(volumeUuid);
22860            packages = mSettings.getVolumePackagesLPr(volumeUuid);
22861        }
22862
22863        for (PackageSetting ps : packages) {
22864            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
22865            synchronized (mInstallLock) {
22866                final PackageParser.Package pkg;
22867                try {
22868                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
22869                    loaded.add(pkg.applicationInfo);
22870
22871                } catch (PackageManagerException e) {
22872                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
22873                }
22874
22875                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
22876                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
22877                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
22878                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
22879                }
22880            }
22881        }
22882
22883        // Reconcile app data for all started/unlocked users
22884        final StorageManager sm = mContext.getSystemService(StorageManager.class);
22885        final UserManager um = mContext.getSystemService(UserManager.class);
22886        UserManagerInternal umInternal = getUserManagerInternal();
22887        for (UserInfo user : um.getUsers()) {
22888            final int flags;
22889            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
22890                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
22891            } else if (umInternal.isUserRunning(user.id)) {
22892                flags = StorageManager.FLAG_STORAGE_DE;
22893            } else {
22894                continue;
22895            }
22896
22897            try {
22898                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
22899                synchronized (mInstallLock) {
22900                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
22901                }
22902            } catch (IllegalStateException e) {
22903                // Device was probably ejected, and we'll process that event momentarily
22904                Slog.w(TAG, "Failed to prepare storage: " + e);
22905            }
22906        }
22907
22908        synchronized (mPackages) {
22909            int updateFlags = UPDATE_PERMISSIONS_ALL;
22910            if (ver.sdkVersion != mSdkVersion) {
22911                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
22912                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
22913                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
22914            }
22915            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
22916
22917            // Yay, everything is now upgraded
22918            ver.forceCurrent();
22919
22920            mSettings.writeLPr();
22921        }
22922
22923        for (PackageFreezer freezer : freezers) {
22924            freezer.close();
22925        }
22926
22927        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
22928        sendResourcesChangedBroadcast(true, false, loaded, null);
22929    }
22930
22931    private void unloadPrivatePackages(final VolumeInfo vol) {
22932        mHandler.post(new Runnable() {
22933            @Override
22934            public void run() {
22935                unloadPrivatePackagesInner(vol);
22936            }
22937        });
22938    }
22939
22940    private void unloadPrivatePackagesInner(VolumeInfo vol) {
22941        final String volumeUuid = vol.fsUuid;
22942        if (TextUtils.isEmpty(volumeUuid)) {
22943            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
22944            return;
22945        }
22946
22947        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
22948        synchronized (mInstallLock) {
22949        synchronized (mPackages) {
22950            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
22951            for (PackageSetting ps : packages) {
22952                if (ps.pkg == null) continue;
22953
22954                final ApplicationInfo info = ps.pkg.applicationInfo;
22955                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
22956                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
22957
22958                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
22959                        "unloadPrivatePackagesInner")) {
22960                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
22961                            false, null)) {
22962                        unloaded.add(info);
22963                    } else {
22964                        Slog.w(TAG, "Failed to unload " + ps.codePath);
22965                    }
22966                }
22967
22968                // Try very hard to release any references to this package
22969                // so we don't risk the system server being killed due to
22970                // open FDs
22971                AttributeCache.instance().removePackage(ps.name);
22972            }
22973
22974            mSettings.writeLPr();
22975        }
22976        }
22977
22978        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
22979        sendResourcesChangedBroadcast(false, false, unloaded, null);
22980
22981        // Try very hard to release any references to this path so we don't risk
22982        // the system server being killed due to open FDs
22983        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
22984
22985        for (int i = 0; i < 3; i++) {
22986            System.gc();
22987            System.runFinalization();
22988        }
22989    }
22990
22991    private void assertPackageKnown(String volumeUuid, String packageName)
22992            throws PackageManagerException {
22993        synchronized (mPackages) {
22994            // Normalize package name to handle renamed packages
22995            packageName = normalizePackageNameLPr(packageName);
22996
22997            final PackageSetting ps = mSettings.mPackages.get(packageName);
22998            if (ps == null) {
22999                throw new PackageManagerException("Package " + packageName + " is unknown");
23000            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23001                throw new PackageManagerException(
23002                        "Package " + packageName + " found on unknown volume " + volumeUuid
23003                                + "; expected volume " + ps.volumeUuid);
23004            }
23005        }
23006    }
23007
23008    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
23009            throws PackageManagerException {
23010        synchronized (mPackages) {
23011            // Normalize package name to handle renamed packages
23012            packageName = normalizePackageNameLPr(packageName);
23013
23014            final PackageSetting ps = mSettings.mPackages.get(packageName);
23015            if (ps == null) {
23016                throw new PackageManagerException("Package " + packageName + " is unknown");
23017            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23018                throw new PackageManagerException(
23019                        "Package " + packageName + " found on unknown volume " + volumeUuid
23020                                + "; expected volume " + ps.volumeUuid);
23021            } else if (!ps.getInstalled(userId)) {
23022                throw new PackageManagerException(
23023                        "Package " + packageName + " not installed for user " + userId);
23024            }
23025        }
23026    }
23027
23028    private List<String> collectAbsoluteCodePaths() {
23029        synchronized (mPackages) {
23030            List<String> codePaths = new ArrayList<>();
23031            final int packageCount = mSettings.mPackages.size();
23032            for (int i = 0; i < packageCount; i++) {
23033                final PackageSetting ps = mSettings.mPackages.valueAt(i);
23034                codePaths.add(ps.codePath.getAbsolutePath());
23035            }
23036            return codePaths;
23037        }
23038    }
23039
23040    /**
23041     * Examine all apps present on given mounted volume, and destroy apps that
23042     * aren't expected, either due to uninstallation or reinstallation on
23043     * another volume.
23044     */
23045    private void reconcileApps(String volumeUuid) {
23046        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
23047        List<File> filesToDelete = null;
23048
23049        final File[] files = FileUtils.listFilesOrEmpty(
23050                Environment.getDataAppDirectory(volumeUuid));
23051        for (File file : files) {
23052            final boolean isPackage = (isApkFile(file) || file.isDirectory())
23053                    && !PackageInstallerService.isStageName(file.getName());
23054            if (!isPackage) {
23055                // Ignore entries which are not packages
23056                continue;
23057            }
23058
23059            String absolutePath = file.getAbsolutePath();
23060
23061            boolean pathValid = false;
23062            final int absoluteCodePathCount = absoluteCodePaths.size();
23063            for (int i = 0; i < absoluteCodePathCount; i++) {
23064                String absoluteCodePath = absoluteCodePaths.get(i);
23065                if (absolutePath.startsWith(absoluteCodePath)) {
23066                    pathValid = true;
23067                    break;
23068                }
23069            }
23070
23071            if (!pathValid) {
23072                if (filesToDelete == null) {
23073                    filesToDelete = new ArrayList<>();
23074                }
23075                filesToDelete.add(file);
23076            }
23077        }
23078
23079        if (filesToDelete != null) {
23080            final int fileToDeleteCount = filesToDelete.size();
23081            for (int i = 0; i < fileToDeleteCount; i++) {
23082                File fileToDelete = filesToDelete.get(i);
23083                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
23084                synchronized (mInstallLock) {
23085                    removeCodePathLI(fileToDelete);
23086                }
23087            }
23088        }
23089    }
23090
23091    /**
23092     * Reconcile all app data for the given user.
23093     * <p>
23094     * Verifies that directories exist and that ownership and labeling is
23095     * correct for all installed apps on all mounted volumes.
23096     */
23097    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
23098        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23099        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
23100            final String volumeUuid = vol.getFsUuid();
23101            synchronized (mInstallLock) {
23102                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
23103            }
23104        }
23105    }
23106
23107    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23108            boolean migrateAppData) {
23109        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
23110    }
23111
23112    /**
23113     * Reconcile all app data on given mounted volume.
23114     * <p>
23115     * Destroys app data that isn't expected, either due to uninstallation or
23116     * reinstallation on another volume.
23117     * <p>
23118     * Verifies that directories exist and that ownership and labeling is
23119     * correct for all installed apps.
23120     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
23121     */
23122    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23123            boolean migrateAppData, boolean onlyCoreApps) {
23124        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
23125                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
23126        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
23127
23128        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
23129        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
23130
23131        // First look for stale data that doesn't belong, and check if things
23132        // have changed since we did our last restorecon
23133        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
23134            if (StorageManager.isFileEncryptedNativeOrEmulated()
23135                    && !StorageManager.isUserKeyUnlocked(userId)) {
23136                throw new RuntimeException(
23137                        "Yikes, someone asked us to reconcile CE storage while " + userId
23138                                + " was still locked; this would have caused massive data loss!");
23139            }
23140
23141            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
23142            for (File file : files) {
23143                final String packageName = file.getName();
23144                try {
23145                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
23146                } catch (PackageManagerException e) {
23147                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
23148                    try {
23149                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
23150                                StorageManager.FLAG_STORAGE_CE, 0);
23151                    } catch (InstallerException e2) {
23152                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
23153                    }
23154                }
23155            }
23156        }
23157        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
23158            final File[] files = FileUtils.listFilesOrEmpty(deDir);
23159            for (File file : files) {
23160                final String packageName = file.getName();
23161                try {
23162                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
23163                } catch (PackageManagerException e) {
23164                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
23165                    try {
23166                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
23167                                StorageManager.FLAG_STORAGE_DE, 0);
23168                    } catch (InstallerException e2) {
23169                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
23170                    }
23171                }
23172            }
23173        }
23174
23175        // Ensure that data directories are ready to roll for all packages
23176        // installed for this volume and user
23177        final List<PackageSetting> packages;
23178        synchronized (mPackages) {
23179            packages = mSettings.getVolumePackagesLPr(volumeUuid);
23180        }
23181        int preparedCount = 0;
23182        for (PackageSetting ps : packages) {
23183            final String packageName = ps.name;
23184            if (ps.pkg == null) {
23185                Slog.w(TAG, "Odd, missing scanned package " + packageName);
23186                // TODO: might be due to legacy ASEC apps; we should circle back
23187                // and reconcile again once they're scanned
23188                continue;
23189            }
23190            // Skip non-core apps if requested
23191            if (onlyCoreApps && !ps.pkg.coreApp) {
23192                result.add(packageName);
23193                continue;
23194            }
23195
23196            if (ps.getInstalled(userId)) {
23197                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
23198                preparedCount++;
23199            }
23200        }
23201
23202        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
23203        return result;
23204    }
23205
23206    /**
23207     * Prepare app data for the given app just after it was installed or
23208     * upgraded. This method carefully only touches users that it's installed
23209     * for, and it forces a restorecon to handle any seinfo changes.
23210     * <p>
23211     * Verifies that directories exist and that ownership and labeling is
23212     * correct for all installed apps. If there is an ownership mismatch, it
23213     * will try recovering system apps by wiping data; third-party app data is
23214     * left intact.
23215     * <p>
23216     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
23217     */
23218    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
23219        final PackageSetting ps;
23220        synchronized (mPackages) {
23221            ps = mSettings.mPackages.get(pkg.packageName);
23222            mSettings.writeKernelMappingLPr(ps);
23223        }
23224
23225        final UserManager um = mContext.getSystemService(UserManager.class);
23226        UserManagerInternal umInternal = getUserManagerInternal();
23227        for (UserInfo user : um.getUsers()) {
23228            final int flags;
23229            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
23230                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
23231            } else if (umInternal.isUserRunning(user.id)) {
23232                flags = StorageManager.FLAG_STORAGE_DE;
23233            } else {
23234                continue;
23235            }
23236
23237            if (ps.getInstalled(user.id)) {
23238                // TODO: when user data is locked, mark that we're still dirty
23239                prepareAppDataLIF(pkg, user.id, flags);
23240            }
23241        }
23242    }
23243
23244    /**
23245     * Prepare app data for the given app.
23246     * <p>
23247     * Verifies that directories exist and that ownership and labeling is
23248     * correct for all installed apps. If there is an ownership mismatch, this
23249     * will try recovering system apps by wiping data; third-party app data is
23250     * left intact.
23251     */
23252    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
23253        if (pkg == null) {
23254            Slog.wtf(TAG, "Package was null!", new Throwable());
23255            return;
23256        }
23257        prepareAppDataLeafLIF(pkg, userId, flags);
23258        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
23259        for (int i = 0; i < childCount; i++) {
23260            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
23261        }
23262    }
23263
23264    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
23265            boolean maybeMigrateAppData) {
23266        prepareAppDataLIF(pkg, userId, flags);
23267
23268        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
23269            // We may have just shuffled around app data directories, so
23270            // prepare them one more time
23271            prepareAppDataLIF(pkg, userId, flags);
23272        }
23273    }
23274
23275    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
23276        if (DEBUG_APP_DATA) {
23277            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
23278                    + Integer.toHexString(flags));
23279        }
23280
23281        final String volumeUuid = pkg.volumeUuid;
23282        final String packageName = pkg.packageName;
23283        final ApplicationInfo app = pkg.applicationInfo;
23284        final int appId = UserHandle.getAppId(app.uid);
23285
23286        Preconditions.checkNotNull(app.seInfo);
23287
23288        long ceDataInode = -1;
23289        try {
23290            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
23291                    appId, app.seInfo, app.targetSdkVersion);
23292        } catch (InstallerException e) {
23293            if (app.isSystemApp()) {
23294                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
23295                        + ", but trying to recover: " + e);
23296                destroyAppDataLeafLIF(pkg, userId, flags);
23297                try {
23298                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
23299                            appId, app.seInfo, app.targetSdkVersion);
23300                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
23301                } catch (InstallerException e2) {
23302                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
23303                }
23304            } else {
23305                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
23306            }
23307        }
23308
23309        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
23310            // TODO: mark this structure as dirty so we persist it!
23311            synchronized (mPackages) {
23312                final PackageSetting ps = mSettings.mPackages.get(packageName);
23313                if (ps != null) {
23314                    ps.setCeDataInode(ceDataInode, userId);
23315                }
23316            }
23317        }
23318
23319        prepareAppDataContentsLeafLIF(pkg, userId, flags);
23320    }
23321
23322    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
23323        if (pkg == null) {
23324            Slog.wtf(TAG, "Package was null!", new Throwable());
23325            return;
23326        }
23327        prepareAppDataContentsLeafLIF(pkg, userId, flags);
23328        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
23329        for (int i = 0; i < childCount; i++) {
23330            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
23331        }
23332    }
23333
23334    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
23335        final String volumeUuid = pkg.volumeUuid;
23336        final String packageName = pkg.packageName;
23337        final ApplicationInfo app = pkg.applicationInfo;
23338
23339        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
23340            // Create a native library symlink only if we have native libraries
23341            // and if the native libraries are 32 bit libraries. We do not provide
23342            // this symlink for 64 bit libraries.
23343            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
23344                final String nativeLibPath = app.nativeLibraryDir;
23345                try {
23346                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
23347                            nativeLibPath, userId);
23348                } catch (InstallerException e) {
23349                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
23350                }
23351            }
23352        }
23353    }
23354
23355    /**
23356     * For system apps on non-FBE devices, this method migrates any existing
23357     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
23358     * requested by the app.
23359     */
23360    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
23361        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
23362                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
23363            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
23364                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
23365            try {
23366                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
23367                        storageTarget);
23368            } catch (InstallerException e) {
23369                logCriticalInfo(Log.WARN,
23370                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
23371            }
23372            return true;
23373        } else {
23374            return false;
23375        }
23376    }
23377
23378    public PackageFreezer freezePackage(String packageName, String killReason) {
23379        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
23380    }
23381
23382    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
23383        return new PackageFreezer(packageName, userId, killReason);
23384    }
23385
23386    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
23387            String killReason) {
23388        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
23389    }
23390
23391    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
23392            String killReason) {
23393        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
23394            return new PackageFreezer();
23395        } else {
23396            return freezePackage(packageName, userId, killReason);
23397        }
23398    }
23399
23400    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
23401            String killReason) {
23402        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
23403    }
23404
23405    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
23406            String killReason) {
23407        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
23408            return new PackageFreezer();
23409        } else {
23410            return freezePackage(packageName, userId, killReason);
23411        }
23412    }
23413
23414    /**
23415     * Class that freezes and kills the given package upon creation, and
23416     * unfreezes it upon closing. This is typically used when doing surgery on
23417     * app code/data to prevent the app from running while you're working.
23418     */
23419    private class PackageFreezer implements AutoCloseable {
23420        private final String mPackageName;
23421        private final PackageFreezer[] mChildren;
23422
23423        private final boolean mWeFroze;
23424
23425        private final AtomicBoolean mClosed = new AtomicBoolean();
23426        private final CloseGuard mCloseGuard = CloseGuard.get();
23427
23428        /**
23429         * Create and return a stub freezer that doesn't actually do anything,
23430         * typically used when someone requested
23431         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
23432         * {@link PackageManager#DELETE_DONT_KILL_APP}.
23433         */
23434        public PackageFreezer() {
23435            mPackageName = null;
23436            mChildren = null;
23437            mWeFroze = false;
23438            mCloseGuard.open("close");
23439        }
23440
23441        public PackageFreezer(String packageName, int userId, String killReason) {
23442            synchronized (mPackages) {
23443                mPackageName = packageName;
23444                mWeFroze = mFrozenPackages.add(mPackageName);
23445
23446                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
23447                if (ps != null) {
23448                    killApplication(ps.name, ps.appId, userId, killReason);
23449                }
23450
23451                final PackageParser.Package p = mPackages.get(packageName);
23452                if (p != null && p.childPackages != null) {
23453                    final int N = p.childPackages.size();
23454                    mChildren = new PackageFreezer[N];
23455                    for (int i = 0; i < N; i++) {
23456                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
23457                                userId, killReason);
23458                    }
23459                } else {
23460                    mChildren = null;
23461                }
23462            }
23463            mCloseGuard.open("close");
23464        }
23465
23466        @Override
23467        protected void finalize() throws Throwable {
23468            try {
23469                mCloseGuard.warnIfOpen();
23470                close();
23471            } finally {
23472                super.finalize();
23473            }
23474        }
23475
23476        @Override
23477        public void close() {
23478            mCloseGuard.close();
23479            if (mClosed.compareAndSet(false, true)) {
23480                synchronized (mPackages) {
23481                    if (mWeFroze) {
23482                        mFrozenPackages.remove(mPackageName);
23483                    }
23484
23485                    if (mChildren != null) {
23486                        for (PackageFreezer freezer : mChildren) {
23487                            freezer.close();
23488                        }
23489                    }
23490                }
23491            }
23492        }
23493    }
23494
23495    /**
23496     * Verify that given package is currently frozen.
23497     */
23498    private void checkPackageFrozen(String packageName) {
23499        synchronized (mPackages) {
23500            if (!mFrozenPackages.contains(packageName)) {
23501                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
23502            }
23503        }
23504    }
23505
23506    @Override
23507    public int movePackage(final String packageName, final String volumeUuid) {
23508        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
23509
23510        final int callingUid = Binder.getCallingUid();
23511        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
23512        final int moveId = mNextMoveId.getAndIncrement();
23513        mHandler.post(new Runnable() {
23514            @Override
23515            public void run() {
23516                try {
23517                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
23518                } catch (PackageManagerException e) {
23519                    Slog.w(TAG, "Failed to move " + packageName, e);
23520                    mMoveCallbacks.notifyStatusChanged(moveId,
23521                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
23522                }
23523            }
23524        });
23525        return moveId;
23526    }
23527
23528    private void movePackageInternal(final String packageName, final String volumeUuid,
23529            final int moveId, final int callingUid, UserHandle user)
23530                    throws PackageManagerException {
23531        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23532        final PackageManager pm = mContext.getPackageManager();
23533
23534        final boolean currentAsec;
23535        final String currentVolumeUuid;
23536        final File codeFile;
23537        final String installerPackageName;
23538        final String packageAbiOverride;
23539        final int appId;
23540        final String seinfo;
23541        final String label;
23542        final int targetSdkVersion;
23543        final PackageFreezer freezer;
23544        final int[] installedUserIds;
23545
23546        // reader
23547        synchronized (mPackages) {
23548            final PackageParser.Package pkg = mPackages.get(packageName);
23549            final PackageSetting ps = mSettings.mPackages.get(packageName);
23550            if (pkg == null
23551                    || ps == null
23552                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
23553                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
23554            }
23555            if (pkg.applicationInfo.isSystemApp()) {
23556                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
23557                        "Cannot move system application");
23558            }
23559
23560            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
23561            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
23562                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
23563            if (isInternalStorage && !allow3rdPartyOnInternal) {
23564                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
23565                        "3rd party apps are not allowed on internal storage");
23566            }
23567
23568            if (pkg.applicationInfo.isExternalAsec()) {
23569                currentAsec = true;
23570                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
23571            } else if (pkg.applicationInfo.isForwardLocked()) {
23572                currentAsec = true;
23573                currentVolumeUuid = "forward_locked";
23574            } else {
23575                currentAsec = false;
23576                currentVolumeUuid = ps.volumeUuid;
23577
23578                final File probe = new File(pkg.codePath);
23579                final File probeOat = new File(probe, "oat");
23580                if (!probe.isDirectory() || !probeOat.isDirectory()) {
23581                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23582                            "Move only supported for modern cluster style installs");
23583                }
23584            }
23585
23586            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
23587                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23588                        "Package already moved to " + volumeUuid);
23589            }
23590            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
23591                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
23592                        "Device admin cannot be moved");
23593            }
23594
23595            if (mFrozenPackages.contains(packageName)) {
23596                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
23597                        "Failed to move already frozen package");
23598            }
23599
23600            codeFile = new File(pkg.codePath);
23601            installerPackageName = ps.installerPackageName;
23602            packageAbiOverride = ps.cpuAbiOverrideString;
23603            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
23604            seinfo = pkg.applicationInfo.seInfo;
23605            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
23606            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
23607            freezer = freezePackage(packageName, "movePackageInternal");
23608            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
23609        }
23610
23611        final Bundle extras = new Bundle();
23612        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
23613        extras.putString(Intent.EXTRA_TITLE, label);
23614        mMoveCallbacks.notifyCreated(moveId, extras);
23615
23616        int installFlags;
23617        final boolean moveCompleteApp;
23618        final File measurePath;
23619
23620        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
23621            installFlags = INSTALL_INTERNAL;
23622            moveCompleteApp = !currentAsec;
23623            measurePath = Environment.getDataAppDirectory(volumeUuid);
23624        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
23625            installFlags = INSTALL_EXTERNAL;
23626            moveCompleteApp = false;
23627            measurePath = storage.getPrimaryPhysicalVolume().getPath();
23628        } else {
23629            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
23630            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
23631                    || !volume.isMountedWritable()) {
23632                freezer.close();
23633                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23634                        "Move location not mounted private volume");
23635            }
23636
23637            Preconditions.checkState(!currentAsec);
23638
23639            installFlags = INSTALL_INTERNAL;
23640            moveCompleteApp = true;
23641            measurePath = Environment.getDataAppDirectory(volumeUuid);
23642        }
23643
23644        final PackageStats stats = new PackageStats(null, -1);
23645        synchronized (mInstaller) {
23646            for (int userId : installedUserIds) {
23647                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
23648                    freezer.close();
23649                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23650                            "Failed to measure package size");
23651                }
23652            }
23653        }
23654
23655        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
23656                + stats.dataSize);
23657
23658        final long startFreeBytes = measurePath.getUsableSpace();
23659        final long sizeBytes;
23660        if (moveCompleteApp) {
23661            sizeBytes = stats.codeSize + stats.dataSize;
23662        } else {
23663            sizeBytes = stats.codeSize;
23664        }
23665
23666        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
23667            freezer.close();
23668            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23669                    "Not enough free space to move");
23670        }
23671
23672        mMoveCallbacks.notifyStatusChanged(moveId, 10);
23673
23674        final CountDownLatch installedLatch = new CountDownLatch(1);
23675        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
23676            @Override
23677            public void onUserActionRequired(Intent intent) throws RemoteException {
23678                throw new IllegalStateException();
23679            }
23680
23681            @Override
23682            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
23683                    Bundle extras) throws RemoteException {
23684                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
23685                        + PackageManager.installStatusToString(returnCode, msg));
23686
23687                installedLatch.countDown();
23688                freezer.close();
23689
23690                final int status = PackageManager.installStatusToPublicStatus(returnCode);
23691                switch (status) {
23692                    case PackageInstaller.STATUS_SUCCESS:
23693                        mMoveCallbacks.notifyStatusChanged(moveId,
23694                                PackageManager.MOVE_SUCCEEDED);
23695                        break;
23696                    case PackageInstaller.STATUS_FAILURE_STORAGE:
23697                        mMoveCallbacks.notifyStatusChanged(moveId,
23698                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
23699                        break;
23700                    default:
23701                        mMoveCallbacks.notifyStatusChanged(moveId,
23702                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
23703                        break;
23704                }
23705            }
23706        };
23707
23708        final MoveInfo move;
23709        if (moveCompleteApp) {
23710            // Kick off a thread to report progress estimates
23711            new Thread() {
23712                @Override
23713                public void run() {
23714                    while (true) {
23715                        try {
23716                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
23717                                break;
23718                            }
23719                        } catch (InterruptedException ignored) {
23720                        }
23721
23722                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
23723                        final int progress = 10 + (int) MathUtils.constrain(
23724                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
23725                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
23726                    }
23727                }
23728            }.start();
23729
23730            final String dataAppName = codeFile.getName();
23731            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
23732                    dataAppName, appId, seinfo, targetSdkVersion);
23733        } else {
23734            move = null;
23735        }
23736
23737        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
23738
23739        final Message msg = mHandler.obtainMessage(INIT_COPY);
23740        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
23741        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
23742                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
23743                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
23744                PackageManager.INSTALL_REASON_UNKNOWN);
23745        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
23746        msg.obj = params;
23747
23748        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
23749                System.identityHashCode(msg.obj));
23750        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
23751                System.identityHashCode(msg.obj));
23752
23753        mHandler.sendMessage(msg);
23754    }
23755
23756    @Override
23757    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
23758        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
23759
23760        final int realMoveId = mNextMoveId.getAndIncrement();
23761        final Bundle extras = new Bundle();
23762        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
23763        mMoveCallbacks.notifyCreated(realMoveId, extras);
23764
23765        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
23766            @Override
23767            public void onCreated(int moveId, Bundle extras) {
23768                // Ignored
23769            }
23770
23771            @Override
23772            public void onStatusChanged(int moveId, int status, long estMillis) {
23773                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
23774            }
23775        };
23776
23777        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23778        storage.setPrimaryStorageUuid(volumeUuid, callback);
23779        return realMoveId;
23780    }
23781
23782    @Override
23783    public int getMoveStatus(int moveId) {
23784        mContext.enforceCallingOrSelfPermission(
23785                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23786        return mMoveCallbacks.mLastStatus.get(moveId);
23787    }
23788
23789    @Override
23790    public void registerMoveCallback(IPackageMoveObserver callback) {
23791        mContext.enforceCallingOrSelfPermission(
23792                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23793        mMoveCallbacks.register(callback);
23794    }
23795
23796    @Override
23797    public void unregisterMoveCallback(IPackageMoveObserver callback) {
23798        mContext.enforceCallingOrSelfPermission(
23799                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23800        mMoveCallbacks.unregister(callback);
23801    }
23802
23803    @Override
23804    public boolean setInstallLocation(int loc) {
23805        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
23806                null);
23807        if (getInstallLocation() == loc) {
23808            return true;
23809        }
23810        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
23811                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
23812            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
23813                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
23814            return true;
23815        }
23816        return false;
23817   }
23818
23819    @Override
23820    public int getInstallLocation() {
23821        // allow instant app access
23822        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
23823                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
23824                PackageHelper.APP_INSTALL_AUTO);
23825    }
23826
23827    /** Called by UserManagerService */
23828    void cleanUpUser(UserManagerService userManager, int userHandle) {
23829        synchronized (mPackages) {
23830            mDirtyUsers.remove(userHandle);
23831            mUserNeedsBadging.delete(userHandle);
23832            mSettings.removeUserLPw(userHandle);
23833            mPendingBroadcasts.remove(userHandle);
23834            mInstantAppRegistry.onUserRemovedLPw(userHandle);
23835            removeUnusedPackagesLPw(userManager, userHandle);
23836        }
23837    }
23838
23839    /**
23840     * We're removing userHandle and would like to remove any downloaded packages
23841     * that are no longer in use by any other user.
23842     * @param userHandle the user being removed
23843     */
23844    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
23845        final boolean DEBUG_CLEAN_APKS = false;
23846        int [] users = userManager.getUserIds();
23847        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
23848        while (psit.hasNext()) {
23849            PackageSetting ps = psit.next();
23850            if (ps.pkg == null) {
23851                continue;
23852            }
23853            final String packageName = ps.pkg.packageName;
23854            // Skip over if system app
23855            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
23856                continue;
23857            }
23858            if (DEBUG_CLEAN_APKS) {
23859                Slog.i(TAG, "Checking package " + packageName);
23860            }
23861            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
23862            if (keep) {
23863                if (DEBUG_CLEAN_APKS) {
23864                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
23865                }
23866            } else {
23867                for (int i = 0; i < users.length; i++) {
23868                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
23869                        keep = true;
23870                        if (DEBUG_CLEAN_APKS) {
23871                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
23872                                    + users[i]);
23873                        }
23874                        break;
23875                    }
23876                }
23877            }
23878            if (!keep) {
23879                if (DEBUG_CLEAN_APKS) {
23880                    Slog.i(TAG, "  Removing package " + packageName);
23881                }
23882                mHandler.post(new Runnable() {
23883                    public void run() {
23884                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
23885                                userHandle, 0);
23886                    } //end run
23887                });
23888            }
23889        }
23890    }
23891
23892    /** Called by UserManagerService */
23893    void createNewUser(int userId, String[] disallowedPackages) {
23894        synchronized (mInstallLock) {
23895            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
23896        }
23897        synchronized (mPackages) {
23898            scheduleWritePackageRestrictionsLocked(userId);
23899            scheduleWritePackageListLocked(userId);
23900            applyFactoryDefaultBrowserLPw(userId);
23901            primeDomainVerificationsLPw(userId);
23902        }
23903    }
23904
23905    void onNewUserCreated(final int userId) {
23906        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
23907        // If permission review for legacy apps is required, we represent
23908        // dagerous permissions for such apps as always granted runtime
23909        // permissions to keep per user flag state whether review is needed.
23910        // Hence, if a new user is added we have to propagate dangerous
23911        // permission grants for these legacy apps.
23912        if (mPermissionReviewRequired) {
23913            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
23914                    | UPDATE_PERMISSIONS_REPLACE_ALL);
23915        }
23916    }
23917
23918    @Override
23919    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
23920        mContext.enforceCallingOrSelfPermission(
23921                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
23922                "Only package verification agents can read the verifier device identity");
23923
23924        synchronized (mPackages) {
23925            return mSettings.getVerifierDeviceIdentityLPw();
23926        }
23927    }
23928
23929    @Override
23930    public void setPermissionEnforced(String permission, boolean enforced) {
23931        // TODO: Now that we no longer change GID for storage, this should to away.
23932        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
23933                "setPermissionEnforced");
23934        if (READ_EXTERNAL_STORAGE.equals(permission)) {
23935            synchronized (mPackages) {
23936                if (mSettings.mReadExternalStorageEnforced == null
23937                        || mSettings.mReadExternalStorageEnforced != enforced) {
23938                    mSettings.mReadExternalStorageEnforced = enforced;
23939                    mSettings.writeLPr();
23940                }
23941            }
23942            // kill any non-foreground processes so we restart them and
23943            // grant/revoke the GID.
23944            final IActivityManager am = ActivityManager.getService();
23945            if (am != null) {
23946                final long token = Binder.clearCallingIdentity();
23947                try {
23948                    am.killProcessesBelowForeground("setPermissionEnforcement");
23949                } catch (RemoteException e) {
23950                } finally {
23951                    Binder.restoreCallingIdentity(token);
23952                }
23953            }
23954        } else {
23955            throw new IllegalArgumentException("No selective enforcement for " + permission);
23956        }
23957    }
23958
23959    @Override
23960    @Deprecated
23961    public boolean isPermissionEnforced(String permission) {
23962        // allow instant applications
23963        return true;
23964    }
23965
23966    @Override
23967    public boolean isStorageLow() {
23968        // allow instant applications
23969        final long token = Binder.clearCallingIdentity();
23970        try {
23971            final DeviceStorageMonitorInternal
23972                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
23973            if (dsm != null) {
23974                return dsm.isMemoryLow();
23975            } else {
23976                return false;
23977            }
23978        } finally {
23979            Binder.restoreCallingIdentity(token);
23980        }
23981    }
23982
23983    @Override
23984    public IPackageInstaller getPackageInstaller() {
23985        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
23986            return null;
23987        }
23988        return mInstallerService;
23989    }
23990
23991    private boolean userNeedsBadging(int userId) {
23992        int index = mUserNeedsBadging.indexOfKey(userId);
23993        if (index < 0) {
23994            final UserInfo userInfo;
23995            final long token = Binder.clearCallingIdentity();
23996            try {
23997                userInfo = sUserManager.getUserInfo(userId);
23998            } finally {
23999                Binder.restoreCallingIdentity(token);
24000            }
24001            final boolean b;
24002            if (userInfo != null && userInfo.isManagedProfile()) {
24003                b = true;
24004            } else {
24005                b = false;
24006            }
24007            mUserNeedsBadging.put(userId, b);
24008            return b;
24009        }
24010        return mUserNeedsBadging.valueAt(index);
24011    }
24012
24013    @Override
24014    public KeySet getKeySetByAlias(String packageName, String alias) {
24015        if (packageName == null || alias == null) {
24016            return null;
24017        }
24018        synchronized(mPackages) {
24019            final PackageParser.Package pkg = mPackages.get(packageName);
24020            if (pkg == null) {
24021                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24022                throw new IllegalArgumentException("Unknown package: " + packageName);
24023            }
24024            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24025            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
24026                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
24027                throw new IllegalArgumentException("Unknown package: " + packageName);
24028            }
24029            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24030            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
24031        }
24032    }
24033
24034    @Override
24035    public KeySet getSigningKeySet(String packageName) {
24036        if (packageName == null) {
24037            return null;
24038        }
24039        synchronized(mPackages) {
24040            final int callingUid = Binder.getCallingUid();
24041            final int callingUserId = UserHandle.getUserId(callingUid);
24042            final PackageParser.Package pkg = mPackages.get(packageName);
24043            if (pkg == null) {
24044                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24045                throw new IllegalArgumentException("Unknown package: " + packageName);
24046            }
24047            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24048            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
24049                // filter and pretend the package doesn't exist
24050                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
24051                        + ", uid:" + callingUid);
24052                throw new IllegalArgumentException("Unknown package: " + packageName);
24053            }
24054            if (pkg.applicationInfo.uid != callingUid
24055                    && Process.SYSTEM_UID != callingUid) {
24056                throw new SecurityException("May not access signing KeySet of other apps.");
24057            }
24058            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24059            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
24060        }
24061    }
24062
24063    @Override
24064    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
24065        final int callingUid = Binder.getCallingUid();
24066        if (getInstantAppPackageName(callingUid) != null) {
24067            return false;
24068        }
24069        if (packageName == null || ks == null) {
24070            return false;
24071        }
24072        synchronized(mPackages) {
24073            final PackageParser.Package pkg = mPackages.get(packageName);
24074            if (pkg == null
24075                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24076                            UserHandle.getUserId(callingUid))) {
24077                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24078                throw new IllegalArgumentException("Unknown package: " + packageName);
24079            }
24080            IBinder ksh = ks.getToken();
24081            if (ksh instanceof KeySetHandle) {
24082                KeySetManagerService ksms = mSettings.mKeySetManagerService;
24083                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
24084            }
24085            return false;
24086        }
24087    }
24088
24089    @Override
24090    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
24091        final int callingUid = Binder.getCallingUid();
24092        if (getInstantAppPackageName(callingUid) != null) {
24093            return false;
24094        }
24095        if (packageName == null || ks == null) {
24096            return false;
24097        }
24098        synchronized(mPackages) {
24099            final PackageParser.Package pkg = mPackages.get(packageName);
24100            if (pkg == null
24101                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24102                            UserHandle.getUserId(callingUid))) {
24103                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24104                throw new IllegalArgumentException("Unknown package: " + packageName);
24105            }
24106            IBinder ksh = ks.getToken();
24107            if (ksh instanceof KeySetHandle) {
24108                KeySetManagerService ksms = mSettings.mKeySetManagerService;
24109                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
24110            }
24111            return false;
24112        }
24113    }
24114
24115    private void deletePackageIfUnusedLPr(final String packageName) {
24116        PackageSetting ps = mSettings.mPackages.get(packageName);
24117        if (ps == null) {
24118            return;
24119        }
24120        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
24121            // TODO Implement atomic delete if package is unused
24122            // It is currently possible that the package will be deleted even if it is installed
24123            // after this method returns.
24124            mHandler.post(new Runnable() {
24125                public void run() {
24126                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
24127                            0, PackageManager.DELETE_ALL_USERS);
24128                }
24129            });
24130        }
24131    }
24132
24133    /**
24134     * Check and throw if the given before/after packages would be considered a
24135     * downgrade.
24136     */
24137    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
24138            throws PackageManagerException {
24139        if (after.versionCode < before.mVersionCode) {
24140            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24141                    "Update version code " + after.versionCode + " is older than current "
24142                    + before.mVersionCode);
24143        } else if (after.versionCode == before.mVersionCode) {
24144            if (after.baseRevisionCode < before.baseRevisionCode) {
24145                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24146                        "Update base revision code " + after.baseRevisionCode
24147                        + " is older than current " + before.baseRevisionCode);
24148            }
24149
24150            if (!ArrayUtils.isEmpty(after.splitNames)) {
24151                for (int i = 0; i < after.splitNames.length; i++) {
24152                    final String splitName = after.splitNames[i];
24153                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
24154                    if (j != -1) {
24155                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
24156                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24157                                    "Update split " + splitName + " revision code "
24158                                    + after.splitRevisionCodes[i] + " is older than current "
24159                                    + before.splitRevisionCodes[j]);
24160                        }
24161                    }
24162                }
24163            }
24164        }
24165    }
24166
24167    private static class MoveCallbacks extends Handler {
24168        private static final int MSG_CREATED = 1;
24169        private static final int MSG_STATUS_CHANGED = 2;
24170
24171        private final RemoteCallbackList<IPackageMoveObserver>
24172                mCallbacks = new RemoteCallbackList<>();
24173
24174        private final SparseIntArray mLastStatus = new SparseIntArray();
24175
24176        public MoveCallbacks(Looper looper) {
24177            super(looper);
24178        }
24179
24180        public void register(IPackageMoveObserver callback) {
24181            mCallbacks.register(callback);
24182        }
24183
24184        public void unregister(IPackageMoveObserver callback) {
24185            mCallbacks.unregister(callback);
24186        }
24187
24188        @Override
24189        public void handleMessage(Message msg) {
24190            final SomeArgs args = (SomeArgs) msg.obj;
24191            final int n = mCallbacks.beginBroadcast();
24192            for (int i = 0; i < n; i++) {
24193                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
24194                try {
24195                    invokeCallback(callback, msg.what, args);
24196                } catch (RemoteException ignored) {
24197                }
24198            }
24199            mCallbacks.finishBroadcast();
24200            args.recycle();
24201        }
24202
24203        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
24204                throws RemoteException {
24205            switch (what) {
24206                case MSG_CREATED: {
24207                    callback.onCreated(args.argi1, (Bundle) args.arg2);
24208                    break;
24209                }
24210                case MSG_STATUS_CHANGED: {
24211                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
24212                    break;
24213                }
24214            }
24215        }
24216
24217        private void notifyCreated(int moveId, Bundle extras) {
24218            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
24219
24220            final SomeArgs args = SomeArgs.obtain();
24221            args.argi1 = moveId;
24222            args.arg2 = extras;
24223            obtainMessage(MSG_CREATED, args).sendToTarget();
24224        }
24225
24226        private void notifyStatusChanged(int moveId, int status) {
24227            notifyStatusChanged(moveId, status, -1);
24228        }
24229
24230        private void notifyStatusChanged(int moveId, int status, long estMillis) {
24231            Slog.v(TAG, "Move " + moveId + " status " + status);
24232
24233            final SomeArgs args = SomeArgs.obtain();
24234            args.argi1 = moveId;
24235            args.argi2 = status;
24236            args.arg3 = estMillis;
24237            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
24238
24239            synchronized (mLastStatus) {
24240                mLastStatus.put(moveId, status);
24241            }
24242        }
24243    }
24244
24245    private final static class OnPermissionChangeListeners extends Handler {
24246        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
24247
24248        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
24249                new RemoteCallbackList<>();
24250
24251        public OnPermissionChangeListeners(Looper looper) {
24252            super(looper);
24253        }
24254
24255        @Override
24256        public void handleMessage(Message msg) {
24257            switch (msg.what) {
24258                case MSG_ON_PERMISSIONS_CHANGED: {
24259                    final int uid = msg.arg1;
24260                    handleOnPermissionsChanged(uid);
24261                } break;
24262            }
24263        }
24264
24265        public void addListenerLocked(IOnPermissionsChangeListener listener) {
24266            mPermissionListeners.register(listener);
24267
24268        }
24269
24270        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
24271            mPermissionListeners.unregister(listener);
24272        }
24273
24274        public void onPermissionsChanged(int uid) {
24275            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
24276                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
24277            }
24278        }
24279
24280        private void handleOnPermissionsChanged(int uid) {
24281            final int count = mPermissionListeners.beginBroadcast();
24282            try {
24283                for (int i = 0; i < count; i++) {
24284                    IOnPermissionsChangeListener callback = mPermissionListeners
24285                            .getBroadcastItem(i);
24286                    try {
24287                        callback.onPermissionsChanged(uid);
24288                    } catch (RemoteException e) {
24289                        Log.e(TAG, "Permission listener is dead", e);
24290                    }
24291                }
24292            } finally {
24293                mPermissionListeners.finishBroadcast();
24294            }
24295        }
24296    }
24297
24298    private class PackageManagerInternalImpl extends PackageManagerInternal {
24299        @Override
24300        public void setLocationPackagesProvider(PackagesProvider provider) {
24301            synchronized (mPackages) {
24302                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
24303            }
24304        }
24305
24306        @Override
24307        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
24308            synchronized (mPackages) {
24309                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
24310            }
24311        }
24312
24313        @Override
24314        public void setSmsAppPackagesProvider(PackagesProvider provider) {
24315            synchronized (mPackages) {
24316                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
24317            }
24318        }
24319
24320        @Override
24321        public void setDialerAppPackagesProvider(PackagesProvider provider) {
24322            synchronized (mPackages) {
24323                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
24324            }
24325        }
24326
24327        @Override
24328        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
24329            synchronized (mPackages) {
24330                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
24331            }
24332        }
24333
24334        @Override
24335        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
24336            synchronized (mPackages) {
24337                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
24338            }
24339        }
24340
24341        @Override
24342        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
24343            synchronized (mPackages) {
24344                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
24345                        packageName, userId);
24346            }
24347        }
24348
24349        @Override
24350        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
24351            synchronized (mPackages) {
24352                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
24353                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
24354                        packageName, userId);
24355            }
24356        }
24357
24358        @Override
24359        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
24360            synchronized (mPackages) {
24361                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
24362                        packageName, userId);
24363            }
24364        }
24365
24366        @Override
24367        public void setKeepUninstalledPackages(final List<String> packageList) {
24368            Preconditions.checkNotNull(packageList);
24369            List<String> removedFromList = null;
24370            synchronized (mPackages) {
24371                if (mKeepUninstalledPackages != null) {
24372                    final int packagesCount = mKeepUninstalledPackages.size();
24373                    for (int i = 0; i < packagesCount; i++) {
24374                        String oldPackage = mKeepUninstalledPackages.get(i);
24375                        if (packageList != null && packageList.contains(oldPackage)) {
24376                            continue;
24377                        }
24378                        if (removedFromList == null) {
24379                            removedFromList = new ArrayList<>();
24380                        }
24381                        removedFromList.add(oldPackage);
24382                    }
24383                }
24384                mKeepUninstalledPackages = new ArrayList<>(packageList);
24385                if (removedFromList != null) {
24386                    final int removedCount = removedFromList.size();
24387                    for (int i = 0; i < removedCount; i++) {
24388                        deletePackageIfUnusedLPr(removedFromList.get(i));
24389                    }
24390                }
24391            }
24392        }
24393
24394        @Override
24395        public boolean isPermissionsReviewRequired(String packageName, int userId) {
24396            synchronized (mPackages) {
24397                // If we do not support permission review, done.
24398                if (!mPermissionReviewRequired) {
24399                    return false;
24400                }
24401
24402                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
24403                if (packageSetting == null) {
24404                    return false;
24405                }
24406
24407                // Permission review applies only to apps not supporting the new permission model.
24408                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
24409                    return false;
24410                }
24411
24412                // Legacy apps have the permission and get user consent on launch.
24413                PermissionsState permissionsState = packageSetting.getPermissionsState();
24414                return permissionsState.isPermissionReviewRequired(userId);
24415            }
24416        }
24417
24418        @Override
24419        public PackageInfo getPackageInfo(
24420                String packageName, int flags, int filterCallingUid, int userId) {
24421            return PackageManagerService.this
24422                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
24423                            flags, filterCallingUid, userId);
24424        }
24425
24426        @Override
24427        public ApplicationInfo getApplicationInfo(
24428                String packageName, int flags, int filterCallingUid, int userId) {
24429            return PackageManagerService.this
24430                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
24431        }
24432
24433        @Override
24434        public ActivityInfo getActivityInfo(
24435                ComponentName component, int flags, int filterCallingUid, int userId) {
24436            return PackageManagerService.this
24437                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
24438        }
24439
24440        @Override
24441        public List<ResolveInfo> queryIntentActivities(
24442                Intent intent, int flags, int filterCallingUid, int userId) {
24443            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
24444            return PackageManagerService.this
24445                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
24446                            userId, false /*resolveForStart*/);
24447        }
24448
24449        @Override
24450        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
24451                int userId) {
24452            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
24453        }
24454
24455        @Override
24456        public void setDeviceAndProfileOwnerPackages(
24457                int deviceOwnerUserId, String deviceOwnerPackage,
24458                SparseArray<String> profileOwnerPackages) {
24459            mProtectedPackages.setDeviceAndProfileOwnerPackages(
24460                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
24461        }
24462
24463        @Override
24464        public boolean isPackageDataProtected(int userId, String packageName) {
24465            return mProtectedPackages.isPackageDataProtected(userId, packageName);
24466        }
24467
24468        @Override
24469        public boolean isPackageEphemeral(int userId, String packageName) {
24470            synchronized (mPackages) {
24471                final PackageSetting ps = mSettings.mPackages.get(packageName);
24472                return ps != null ? ps.getInstantApp(userId) : false;
24473            }
24474        }
24475
24476        @Override
24477        public boolean wasPackageEverLaunched(String packageName, int userId) {
24478            synchronized (mPackages) {
24479                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
24480            }
24481        }
24482
24483        @Override
24484        public void grantRuntimePermission(String packageName, String name, int userId,
24485                boolean overridePolicy) {
24486            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
24487                    overridePolicy);
24488        }
24489
24490        @Override
24491        public void revokeRuntimePermission(String packageName, String name, int userId,
24492                boolean overridePolicy) {
24493            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
24494                    overridePolicy);
24495        }
24496
24497        @Override
24498        public String getNameForUid(int uid) {
24499            return PackageManagerService.this.getNameForUid(uid);
24500        }
24501
24502        @Override
24503        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
24504                Intent origIntent, String resolvedType, String callingPackage,
24505                Bundle verificationBundle, int userId) {
24506            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
24507                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
24508                    userId);
24509        }
24510
24511        @Override
24512        public void grantEphemeralAccess(int userId, Intent intent,
24513                int targetAppId, int ephemeralAppId) {
24514            synchronized (mPackages) {
24515                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
24516                        targetAppId, ephemeralAppId);
24517            }
24518        }
24519
24520        @Override
24521        public boolean isInstantAppInstallerComponent(ComponentName component) {
24522            synchronized (mPackages) {
24523                return mInstantAppInstallerActivity != null
24524                        && mInstantAppInstallerActivity.getComponentName().equals(component);
24525            }
24526        }
24527
24528        @Override
24529        public void pruneInstantApps() {
24530            mInstantAppRegistry.pruneInstantApps();
24531        }
24532
24533        @Override
24534        public String getSetupWizardPackageName() {
24535            return mSetupWizardPackage;
24536        }
24537
24538        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
24539            if (policy != null) {
24540                mExternalSourcesPolicy = policy;
24541            }
24542        }
24543
24544        @Override
24545        public boolean isPackagePersistent(String packageName) {
24546            synchronized (mPackages) {
24547                PackageParser.Package pkg = mPackages.get(packageName);
24548                return pkg != null
24549                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
24550                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
24551                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
24552                        : false;
24553            }
24554        }
24555
24556        @Override
24557        public List<PackageInfo> getOverlayPackages(int userId) {
24558            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
24559            synchronized (mPackages) {
24560                for (PackageParser.Package p : mPackages.values()) {
24561                    if (p.mOverlayTarget != null) {
24562                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
24563                        if (pkg != null) {
24564                            overlayPackages.add(pkg);
24565                        }
24566                    }
24567                }
24568            }
24569            return overlayPackages;
24570        }
24571
24572        @Override
24573        public List<String> getTargetPackageNames(int userId) {
24574            List<String> targetPackages = new ArrayList<>();
24575            synchronized (mPackages) {
24576                for (PackageParser.Package p : mPackages.values()) {
24577                    if (p.mOverlayTarget == null) {
24578                        targetPackages.add(p.packageName);
24579                    }
24580                }
24581            }
24582            return targetPackages;
24583        }
24584
24585        @Override
24586        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
24587                @Nullable List<String> overlayPackageNames) {
24588            synchronized (mPackages) {
24589                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
24590                    Slog.e(TAG, "failed to find package " + targetPackageName);
24591                    return false;
24592                }
24593                ArrayList<String> overlayPaths = null;
24594                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
24595                    final int N = overlayPackageNames.size();
24596                    overlayPaths = new ArrayList<>(N);
24597                    for (int i = 0; i < N; i++) {
24598                        final String packageName = overlayPackageNames.get(i);
24599                        final PackageParser.Package pkg = mPackages.get(packageName);
24600                        if (pkg == null) {
24601                            Slog.e(TAG, "failed to find package " + packageName);
24602                            return false;
24603                        }
24604                        overlayPaths.add(pkg.baseCodePath);
24605                    }
24606                }
24607
24608                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
24609                String[] frameworkOverlayPaths = null;
24610                if (!"android".equals(targetPackageName)) {
24611                    frameworkOverlayPaths =
24612                            mSettings.mPackages.get("android").getOverlayPaths(userId);
24613                }
24614                ps.setOverlayPaths(overlayPaths, frameworkOverlayPaths, userId);
24615                return true;
24616            }
24617        }
24618
24619        @Override
24620        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
24621                int flags, int userId) {
24622            return resolveIntentInternal(
24623                    intent, resolvedType, flags, userId, true /*resolveForStart*/);
24624        }
24625
24626        @Override
24627        public ResolveInfo resolveService(Intent intent, String resolvedType,
24628                int flags, int userId, int callingUid) {
24629            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
24630        }
24631
24632        @Override
24633        public void addIsolatedUid(int isolatedUid, int ownerUid) {
24634            synchronized (mPackages) {
24635                mIsolatedOwners.put(isolatedUid, ownerUid);
24636            }
24637        }
24638
24639        @Override
24640        public void removeIsolatedUid(int isolatedUid) {
24641            synchronized (mPackages) {
24642                mIsolatedOwners.delete(isolatedUid);
24643            }
24644        }
24645
24646        @Override
24647        public int getUidTargetSdkVersion(int uid) {
24648            synchronized (mPackages) {
24649                return getUidTargetSdkVersionLockedLPr(uid);
24650            }
24651        }
24652
24653        @Override
24654        public boolean canAccessInstantApps(int callingUid, int userId) {
24655            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
24656        }
24657    }
24658
24659    @Override
24660    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
24661        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
24662        synchronized (mPackages) {
24663            final long identity = Binder.clearCallingIdentity();
24664            try {
24665                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
24666                        packageNames, userId);
24667            } finally {
24668                Binder.restoreCallingIdentity(identity);
24669            }
24670        }
24671    }
24672
24673    @Override
24674    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
24675        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
24676        synchronized (mPackages) {
24677            final long identity = Binder.clearCallingIdentity();
24678            try {
24679                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr(
24680                        packageNames, userId);
24681            } finally {
24682                Binder.restoreCallingIdentity(identity);
24683            }
24684        }
24685    }
24686
24687    private static void enforceSystemOrPhoneCaller(String tag) {
24688        int callingUid = Binder.getCallingUid();
24689        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
24690            throw new SecurityException(
24691                    "Cannot call " + tag + " from UID " + callingUid);
24692        }
24693    }
24694
24695    boolean isHistoricalPackageUsageAvailable() {
24696        return mPackageUsage.isHistoricalPackageUsageAvailable();
24697    }
24698
24699    /**
24700     * Return a <b>copy</b> of the collection of packages known to the package manager.
24701     * @return A copy of the values of mPackages.
24702     */
24703    Collection<PackageParser.Package> getPackages() {
24704        synchronized (mPackages) {
24705            return new ArrayList<>(mPackages.values());
24706        }
24707    }
24708
24709    /**
24710     * Logs process start information (including base APK hash) to the security log.
24711     * @hide
24712     */
24713    @Override
24714    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
24715            String apkFile, int pid) {
24716        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24717            return;
24718        }
24719        if (!SecurityLog.isLoggingEnabled()) {
24720            return;
24721        }
24722        Bundle data = new Bundle();
24723        data.putLong("startTimestamp", System.currentTimeMillis());
24724        data.putString("processName", processName);
24725        data.putInt("uid", uid);
24726        data.putString("seinfo", seinfo);
24727        data.putString("apkFile", apkFile);
24728        data.putInt("pid", pid);
24729        Message msg = mProcessLoggingHandler.obtainMessage(
24730                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
24731        msg.setData(data);
24732        mProcessLoggingHandler.sendMessage(msg);
24733    }
24734
24735    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
24736        return mCompilerStats.getPackageStats(pkgName);
24737    }
24738
24739    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
24740        return getOrCreateCompilerPackageStats(pkg.packageName);
24741    }
24742
24743    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
24744        return mCompilerStats.getOrCreatePackageStats(pkgName);
24745    }
24746
24747    public void deleteCompilerPackageStats(String pkgName) {
24748        mCompilerStats.deletePackageStats(pkgName);
24749    }
24750
24751    @Override
24752    public int getInstallReason(String packageName, int userId) {
24753        final int callingUid = Binder.getCallingUid();
24754        enforceCrossUserPermission(callingUid, userId,
24755                true /* requireFullPermission */, false /* checkShell */,
24756                "get install reason");
24757        synchronized (mPackages) {
24758            final PackageSetting ps = mSettings.mPackages.get(packageName);
24759            if (filterAppAccessLPr(ps, callingUid, userId)) {
24760                return PackageManager.INSTALL_REASON_UNKNOWN;
24761            }
24762            if (ps != null) {
24763                return ps.getInstallReason(userId);
24764            }
24765        }
24766        return PackageManager.INSTALL_REASON_UNKNOWN;
24767    }
24768
24769    @Override
24770    public boolean canRequestPackageInstalls(String packageName, int userId) {
24771        return canRequestPackageInstallsInternal(packageName, 0, userId,
24772                true /* throwIfPermNotDeclared*/);
24773    }
24774
24775    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
24776            boolean throwIfPermNotDeclared) {
24777        int callingUid = Binder.getCallingUid();
24778        int uid = getPackageUid(packageName, 0, userId);
24779        if (callingUid != uid && callingUid != Process.ROOT_UID
24780                && callingUid != Process.SYSTEM_UID) {
24781            throw new SecurityException(
24782                    "Caller uid " + callingUid + " does not own package " + packageName);
24783        }
24784        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
24785        if (info == null) {
24786            return false;
24787        }
24788        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
24789            return false;
24790        }
24791        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
24792        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
24793        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
24794            if (throwIfPermNotDeclared) {
24795                throw new SecurityException("Need to declare " + appOpPermission
24796                        + " to call this api");
24797            } else {
24798                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
24799                return false;
24800            }
24801        }
24802        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
24803            return false;
24804        }
24805        if (mExternalSourcesPolicy != null) {
24806            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
24807            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
24808                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
24809            }
24810        }
24811        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
24812    }
24813
24814    @Override
24815    public ComponentName getInstantAppResolverSettingsComponent() {
24816        return mInstantAppResolverSettingsComponent;
24817    }
24818
24819    @Override
24820    public ComponentName getInstantAppInstallerComponent() {
24821        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24822            return null;
24823        }
24824        return mInstantAppInstallerActivity == null
24825                ? null : mInstantAppInstallerActivity.getComponentName();
24826    }
24827
24828    @Override
24829    public String getInstantAppAndroidId(String packageName, int userId) {
24830        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
24831                "getInstantAppAndroidId");
24832        enforceCrossUserPermission(Binder.getCallingUid(), userId,
24833                true /* requireFullPermission */, false /* checkShell */,
24834                "getInstantAppAndroidId");
24835        // Make sure the target is an Instant App.
24836        if (!isInstantApp(packageName, userId)) {
24837            return null;
24838        }
24839        synchronized (mPackages) {
24840            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
24841        }
24842    }
24843}
24844
24845interface PackageSender {
24846    void sendPackageBroadcast(final String action, final String pkg,
24847        final Bundle extras, final int flags, final String targetPkg,
24848        final IIntentReceiver finishedReceiver, final int[] userIds);
24849    void sendPackageAddedForNewUsers(String packageName, boolean isSystem,
24850        int appId, int... userIds);
24851}
24852