PackageManagerService.java revision e2437036a653261aadd2b28f524386340f96b66d
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.DELETE_PACKAGES;
20import static android.Manifest.permission.INSTALL_PACKAGES;
21import static android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS;
22import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
23import static android.Manifest.permission.REQUEST_DELETE_PACKAGES;
24import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
25import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
27import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
28import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
29import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
30import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
31import static android.content.pm.PackageManager.DELETE_KEEP_DATA;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
33import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
34import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
35import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
36import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
37import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
38import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
39import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
40import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
41import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
42import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
43import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
44import static android.content.pm.PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID;
45import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
46import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
47import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
48import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
49import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
50import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
51import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
52import static android.content.pm.PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE;
53import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
54import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
55import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
56import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
57import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
58import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
59import static android.content.pm.PackageManager.INSTALL_INTERNAL;
60import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
61import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
62import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
63import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
64import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
65import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
66import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
67import static android.content.pm.PackageManager.MATCH_ALL;
68import static android.content.pm.PackageManager.MATCH_ANY_USER;
69import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
70import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
71import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
72import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
73import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
74import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES;
75import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
76import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
77import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL;
78import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
79import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
80import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
81import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
82import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
83import static android.content.pm.PackageManager.PERMISSION_DENIED;
84import static android.content.pm.PackageManager.PERMISSION_GRANTED;
85import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
86import static android.content.pm.PackageParser.isApkFile;
87import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
88import static android.system.OsConstants.O_CREAT;
89import static android.system.OsConstants.O_RDWR;
90import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
91import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
92import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
93import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
94import static com.android.internal.util.ArrayUtils.appendInt;
95import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
96import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
97import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
98import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
99import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
100import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
101import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter;
102import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
103import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
104import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
105import static dalvik.system.DexFile.getNonProfileGuidedCompilerFilter;
106
107import android.Manifest;
108import android.annotation.IntDef;
109import android.annotation.NonNull;
110import android.annotation.Nullable;
111import android.app.ActivityManager;
112import android.app.AppOpsManager;
113import android.app.IActivityManager;
114import android.app.ResourcesManager;
115import android.app.admin.IDevicePolicyManager;
116import android.app.admin.SecurityLog;
117import android.app.backup.IBackupManager;
118import android.content.BroadcastReceiver;
119import android.content.ComponentName;
120import android.content.ContentResolver;
121import android.content.Context;
122import android.content.IIntentReceiver;
123import android.content.Intent;
124import android.content.IntentFilter;
125import android.content.IntentSender;
126import android.content.IntentSender.SendIntentException;
127import android.content.ServiceConnection;
128import android.content.pm.ActivityInfo;
129import android.content.pm.ApplicationInfo;
130import android.content.pm.AppsQueryHelper;
131import android.content.pm.AuxiliaryResolveInfo;
132import android.content.pm.ChangedPackages;
133import android.content.pm.FallbackCategoryProvider;
134import android.content.pm.FeatureInfo;
135import android.content.pm.IOnPermissionsChangeListener;
136import android.content.pm.IPackageDataObserver;
137import android.content.pm.IPackageDeleteObserver;
138import android.content.pm.IPackageDeleteObserver2;
139import android.content.pm.IPackageInstallObserver2;
140import android.content.pm.IPackageInstaller;
141import android.content.pm.IPackageManager;
142import android.content.pm.IPackageMoveObserver;
143import android.content.pm.IPackageStatsObserver;
144import android.content.pm.InstantAppInfo;
145import android.content.pm.InstantAppRequest;
146import android.content.pm.InstantAppResolveInfo;
147import android.content.pm.InstrumentationInfo;
148import android.content.pm.IntentFilterVerificationInfo;
149import android.content.pm.KeySet;
150import android.content.pm.PackageCleanItem;
151import android.content.pm.PackageInfo;
152import android.content.pm.PackageInfoLite;
153import android.content.pm.PackageInstaller;
154import android.content.pm.PackageManager;
155import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
156import android.content.pm.PackageManagerInternal;
157import android.content.pm.PackageParser;
158import android.content.pm.PackageParser.ActivityIntentInfo;
159import android.content.pm.PackageParser.PackageLite;
160import android.content.pm.PackageParser.PackageParserException;
161import android.content.pm.PackageStats;
162import android.content.pm.PackageUserState;
163import android.content.pm.ParceledListSlice;
164import android.content.pm.PermissionGroupInfo;
165import android.content.pm.PermissionInfo;
166import android.content.pm.ProviderInfo;
167import android.content.pm.ResolveInfo;
168import android.content.pm.ServiceInfo;
169import android.content.pm.SharedLibraryInfo;
170import android.content.pm.Signature;
171import android.content.pm.UserInfo;
172import android.content.pm.VerifierDeviceIdentity;
173import android.content.pm.VerifierInfo;
174import android.content.pm.VersionedPackage;
175import android.content.res.Resources;
176import android.database.ContentObserver;
177import android.graphics.Bitmap;
178import android.hardware.display.DisplayManager;
179import android.net.Uri;
180import android.os.Binder;
181import android.os.Build;
182import android.os.Bundle;
183import android.os.Debug;
184import android.os.Environment;
185import android.os.Environment.UserEnvironment;
186import android.os.FileUtils;
187import android.os.Handler;
188import android.os.IBinder;
189import android.os.Looper;
190import android.os.Message;
191import android.os.Parcel;
192import android.os.ParcelFileDescriptor;
193import android.os.PatternMatcher;
194import android.os.Process;
195import android.os.RemoteCallbackList;
196import android.os.RemoteException;
197import android.os.ResultReceiver;
198import android.os.SELinux;
199import android.os.ServiceManager;
200import android.os.ShellCallback;
201import android.os.SystemClock;
202import android.os.SystemProperties;
203import android.os.Trace;
204import android.os.UserHandle;
205import android.os.UserManager;
206import android.os.UserManagerInternal;
207import android.os.storage.IStorageManager;
208import android.os.storage.StorageEventListener;
209import android.os.storage.StorageManager;
210import android.os.storage.StorageManagerInternal;
211import android.os.storage.VolumeInfo;
212import android.os.storage.VolumeRecord;
213import android.provider.Settings.Global;
214import android.provider.Settings.Secure;
215import android.security.KeyStore;
216import android.security.SystemKeyStore;
217import android.service.pm.PackageServiceDumpProto;
218import android.system.ErrnoException;
219import android.system.Os;
220import android.text.TextUtils;
221import android.text.format.DateUtils;
222import android.util.ArrayMap;
223import android.util.ArraySet;
224import android.util.Base64;
225import android.util.BootTimingsTraceLog;
226import android.util.DisplayMetrics;
227import android.util.EventLog;
228import android.util.ExceptionUtils;
229import android.util.Log;
230import android.util.LogPrinter;
231import android.util.MathUtils;
232import android.util.PackageUtils;
233import android.util.Pair;
234import android.util.PrintStreamPrinter;
235import android.util.Slog;
236import android.util.SparseArray;
237import android.util.SparseBooleanArray;
238import android.util.SparseIntArray;
239import android.util.Xml;
240import android.util.jar.StrictJarFile;
241import android.util.proto.ProtoOutputStream;
242import android.view.Display;
243
244import com.android.internal.R;
245import com.android.internal.annotations.GuardedBy;
246import com.android.internal.app.IMediaContainerService;
247import com.android.internal.app.ResolverActivity;
248import com.android.internal.content.NativeLibraryHelper;
249import com.android.internal.content.PackageHelper;
250import com.android.internal.logging.MetricsLogger;
251import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
252import com.android.internal.os.IParcelFileDescriptorFactory;
253import com.android.internal.os.RoSystemProperties;
254import com.android.internal.os.SomeArgs;
255import com.android.internal.os.Zygote;
256import com.android.internal.telephony.CarrierAppUtils;
257import com.android.internal.util.ArrayUtils;
258import com.android.internal.util.ConcurrentUtils;
259import com.android.internal.util.DumpUtils;
260import com.android.internal.util.FastPrintWriter;
261import com.android.internal.util.FastXmlSerializer;
262import com.android.internal.util.IndentingPrintWriter;
263import com.android.internal.util.Preconditions;
264import com.android.internal.util.XmlUtils;
265import com.android.server.AttributeCache;
266import com.android.server.DeviceIdleController;
267import com.android.server.EventLogTags;
268import com.android.server.FgThread;
269import com.android.server.IntentResolver;
270import com.android.server.LocalServices;
271import com.android.server.LockGuard;
272import com.android.server.ServiceThread;
273import com.android.server.SystemConfig;
274import com.android.server.SystemServerInitThreadPool;
275import com.android.server.Watchdog;
276import com.android.server.net.NetworkPolicyManagerInternal;
277import com.android.server.pm.Installer.InstallerException;
278import com.android.server.pm.PermissionsState.PermissionState;
279import com.android.server.pm.Settings.DatabaseVersion;
280import com.android.server.pm.Settings.VersionInfo;
281import com.android.server.pm.dex.DexManager;
282import com.android.server.storage.DeviceStorageMonitorInternal;
283
284import dalvik.system.CloseGuard;
285import dalvik.system.DexFile;
286import dalvik.system.VMRuntime;
287
288import libcore.io.IoUtils;
289import libcore.util.EmptyArray;
290
291import org.xmlpull.v1.XmlPullParser;
292import org.xmlpull.v1.XmlPullParserException;
293import org.xmlpull.v1.XmlSerializer;
294
295import java.io.BufferedOutputStream;
296import java.io.BufferedReader;
297import java.io.ByteArrayInputStream;
298import java.io.ByteArrayOutputStream;
299import java.io.File;
300import java.io.FileDescriptor;
301import java.io.FileInputStream;
302import java.io.FileOutputStream;
303import java.io.FileReader;
304import java.io.FilenameFilter;
305import java.io.IOException;
306import java.io.PrintWriter;
307import java.lang.annotation.Retention;
308import java.lang.annotation.RetentionPolicy;
309import java.nio.charset.StandardCharsets;
310import java.security.DigestInputStream;
311import java.security.MessageDigest;
312import java.security.NoSuchAlgorithmException;
313import java.security.PublicKey;
314import java.security.SecureRandom;
315import java.security.cert.Certificate;
316import java.security.cert.CertificateEncodingException;
317import java.security.cert.CertificateException;
318import java.text.SimpleDateFormat;
319import java.util.ArrayList;
320import java.util.Arrays;
321import java.util.Collection;
322import java.util.Collections;
323import java.util.Comparator;
324import java.util.Date;
325import java.util.HashMap;
326import java.util.HashSet;
327import java.util.Iterator;
328import java.util.List;
329import java.util.Map;
330import java.util.Objects;
331import java.util.Set;
332import java.util.concurrent.CountDownLatch;
333import java.util.concurrent.Future;
334import java.util.concurrent.TimeUnit;
335import java.util.concurrent.atomic.AtomicBoolean;
336import java.util.concurrent.atomic.AtomicInteger;
337
338/**
339 * Keep track of all those APKs everywhere.
340 * <p>
341 * Internally there are two important locks:
342 * <ul>
343 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
344 * and other related state. It is a fine-grained lock that should only be held
345 * momentarily, as it's one of the most contended locks in the system.
346 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
347 * operations typically involve heavy lifting of application data on disk. Since
348 * {@code installd} is single-threaded, and it's operations can often be slow,
349 * this lock should never be acquired while already holding {@link #mPackages}.
350 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
351 * holding {@link #mInstallLock}.
352 * </ul>
353 * Many internal methods rely on the caller to hold the appropriate locks, and
354 * this contract is expressed through method name suffixes:
355 * <ul>
356 * <li>fooLI(): the caller must hold {@link #mInstallLock}
357 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
358 * being modified must be frozen
359 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
360 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
361 * </ul>
362 * <p>
363 * Because this class is very central to the platform's security; please run all
364 * CTS and unit tests whenever making modifications:
365 *
366 * <pre>
367 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
368 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
369 * </pre>
370 */
371public class PackageManagerService extends IPackageManager.Stub
372        implements PackageSender {
373    static final String TAG = "PackageManager";
374    static final boolean DEBUG_SETTINGS = false;
375    static final boolean DEBUG_PREFERRED = false;
376    static final boolean DEBUG_UPGRADE = false;
377    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
378    private static final boolean DEBUG_BACKUP = false;
379    private static final boolean DEBUG_INSTALL = false;
380    private static final boolean DEBUG_REMOVE = false;
381    private static final boolean DEBUG_BROADCASTS = false;
382    private static final boolean DEBUG_SHOW_INFO = false;
383    private static final boolean DEBUG_PACKAGE_INFO = false;
384    private static final boolean DEBUG_INTENT_MATCHING = false;
385    private static final boolean DEBUG_PACKAGE_SCANNING = false;
386    private static final boolean DEBUG_VERIFY = false;
387    private static final boolean DEBUG_FILTERS = false;
388    private static final boolean DEBUG_PERMISSIONS = false;
389    private static final boolean DEBUG_SHARED_LIBRARIES = false;
390
391    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
392    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
393    // user, but by default initialize to this.
394    public static final boolean DEBUG_DEXOPT = false;
395
396    private static final boolean DEBUG_ABI_SELECTION = false;
397    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
398    private static final boolean DEBUG_TRIAGED_MISSING = false;
399    private static final boolean DEBUG_APP_DATA = false;
400
401    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
402    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
403
404    private static final boolean HIDE_EPHEMERAL_APIS = false;
405
406    private static final boolean ENABLE_FREE_CACHE_V2 =
407            SystemProperties.getBoolean("fw.free_cache_v2", true);
408
409    private static final int RADIO_UID = Process.PHONE_UID;
410    private static final int LOG_UID = Process.LOG_UID;
411    private static final int NFC_UID = Process.NFC_UID;
412    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
413    private static final int SHELL_UID = Process.SHELL_UID;
414
415    // Cap the size of permission trees that 3rd party apps can define
416    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
417
418    // Suffix used during package installation when copying/moving
419    // package apks to install directory.
420    private static final String INSTALL_PACKAGE_SUFFIX = "-";
421
422    static final int SCAN_NO_DEX = 1<<1;
423    static final int SCAN_FORCE_DEX = 1<<2;
424    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
425    static final int SCAN_NEW_INSTALL = 1<<4;
426    static final int SCAN_UPDATE_TIME = 1<<5;
427    static final int SCAN_BOOTING = 1<<6;
428    static final int SCAN_TRUSTED_OVERLAY = 1<<7;
429    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8;
430    static final int SCAN_REPLACING = 1<<9;
431    static final int SCAN_REQUIRE_KNOWN = 1<<10;
432    static final int SCAN_MOVE = 1<<11;
433    static final int SCAN_INITIAL = 1<<12;
434    static final int SCAN_CHECK_ONLY = 1<<13;
435    static final int SCAN_DONT_KILL_APP = 1<<14;
436    static final int SCAN_IGNORE_FROZEN = 1<<15;
437    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16;
438    static final int SCAN_AS_INSTANT_APP = 1<<17;
439    static final int SCAN_AS_FULL_APP = 1<<18;
440    /** Should not be with the scan flags */
441    static final int FLAGS_REMOVE_CHATTY = 1<<31;
442
443    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
444
445    private static final int[] EMPTY_INT_ARRAY = new int[0];
446
447    private static final int TYPE_UNKNOWN = 0;
448    private static final int TYPE_ACTIVITY = 1;
449    private static final int TYPE_RECEIVER = 2;
450    private static final int TYPE_SERVICE = 3;
451    private static final int TYPE_PROVIDER = 4;
452    @IntDef(prefix = { "TYPE_" }, value = {
453            TYPE_UNKNOWN,
454            TYPE_ACTIVITY,
455            TYPE_RECEIVER,
456            TYPE_SERVICE,
457            TYPE_PROVIDER,
458    })
459    @Retention(RetentionPolicy.SOURCE)
460    public @interface ComponentType {}
461
462    /**
463     * Timeout (in milliseconds) after which the watchdog should declare that
464     * our handler thread is wedged.  The usual default for such things is one
465     * minute but we sometimes do very lengthy I/O operations on this thread,
466     * such as installing multi-gigabyte applications, so ours needs to be longer.
467     */
468    static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
469
470    /**
471     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
472     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
473     * settings entry if available, otherwise we use the hardcoded default.  If it's been
474     * more than this long since the last fstrim, we force one during the boot sequence.
475     *
476     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
477     * one gets run at the next available charging+idle time.  This final mandatory
478     * no-fstrim check kicks in only of the other scheduling criteria is never met.
479     */
480    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
481
482    /**
483     * Whether verification is enabled by default.
484     */
485    private static final boolean DEFAULT_VERIFY_ENABLE = true;
486
487    /**
488     * The default maximum time to wait for the verification agent to return in
489     * milliseconds.
490     */
491    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
492
493    /**
494     * The default response for package verification timeout.
495     *
496     * This can be either PackageManager.VERIFICATION_ALLOW or
497     * PackageManager.VERIFICATION_REJECT.
498     */
499    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
500
501    static final String PLATFORM_PACKAGE_NAME = "android";
502
503    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
504
505    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
506            DEFAULT_CONTAINER_PACKAGE,
507            "com.android.defcontainer.DefaultContainerService");
508
509    private static final String KILL_APP_REASON_GIDS_CHANGED =
510            "permission grant or revoke changed gids";
511
512    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
513            "permissions revoked";
514
515    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
516
517    private static final String PACKAGE_SCHEME = "package";
518
519    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
520
521    /** Permission grant: not grant the permission. */
522    private static final int GRANT_DENIED = 1;
523
524    /** Permission grant: grant the permission as an install permission. */
525    private static final int GRANT_INSTALL = 2;
526
527    /** Permission grant: grant the permission as a runtime one. */
528    private static final int GRANT_RUNTIME = 3;
529
530    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
531    private static final int GRANT_UPGRADE = 4;
532
533    /** Canonical intent used to identify what counts as a "web browser" app */
534    private static final Intent sBrowserIntent;
535    static {
536        sBrowserIntent = new Intent();
537        sBrowserIntent.setAction(Intent.ACTION_VIEW);
538        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
539        sBrowserIntent.setData(Uri.parse("http:"));
540    }
541
542    /**
543     * The set of all protected actions [i.e. those actions for which a high priority
544     * intent filter is disallowed].
545     */
546    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
547    static {
548        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
549        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
550        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
551        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
552    }
553
554    // Compilation reasons.
555    public static final int REASON_FIRST_BOOT = 0;
556    public static final int REASON_BOOT = 1;
557    public static final int REASON_INSTALL = 2;
558    public static final int REASON_BACKGROUND_DEXOPT = 3;
559    public static final int REASON_AB_OTA = 4;
560
561    public static final int REASON_LAST = REASON_AB_OTA;
562
563    /** All dangerous permission names in the same order as the events in MetricsEvent */
564    private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList(
565            Manifest.permission.READ_CALENDAR,
566            Manifest.permission.WRITE_CALENDAR,
567            Manifest.permission.CAMERA,
568            Manifest.permission.READ_CONTACTS,
569            Manifest.permission.WRITE_CONTACTS,
570            Manifest.permission.GET_ACCOUNTS,
571            Manifest.permission.ACCESS_FINE_LOCATION,
572            Manifest.permission.ACCESS_COARSE_LOCATION,
573            Manifest.permission.RECORD_AUDIO,
574            Manifest.permission.READ_PHONE_STATE,
575            Manifest.permission.CALL_PHONE,
576            Manifest.permission.READ_CALL_LOG,
577            Manifest.permission.WRITE_CALL_LOG,
578            Manifest.permission.ADD_VOICEMAIL,
579            Manifest.permission.USE_SIP,
580            Manifest.permission.PROCESS_OUTGOING_CALLS,
581            Manifest.permission.READ_CELL_BROADCASTS,
582            Manifest.permission.BODY_SENSORS,
583            Manifest.permission.SEND_SMS,
584            Manifest.permission.RECEIVE_SMS,
585            Manifest.permission.READ_SMS,
586            Manifest.permission.RECEIVE_WAP_PUSH,
587            Manifest.permission.RECEIVE_MMS,
588            Manifest.permission.READ_EXTERNAL_STORAGE,
589            Manifest.permission.WRITE_EXTERNAL_STORAGE,
590            Manifest.permission.READ_PHONE_NUMBERS,
591            Manifest.permission.ANSWER_PHONE_CALLS);
592
593
594    /**
595     * Version number for the package parser cache. Increment this whenever the format or
596     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
597     */
598    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
599
600    /**
601     * Whether the package parser cache is enabled.
602     */
603    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
604
605    final ServiceThread mHandlerThread;
606
607    final PackageHandler mHandler;
608
609    private final ProcessLoggingHandler mProcessLoggingHandler;
610
611    /**
612     * Messages for {@link #mHandler} that need to wait for system ready before
613     * being dispatched.
614     */
615    private ArrayList<Message> mPostSystemReadyMessages;
616
617    final int mSdkVersion = Build.VERSION.SDK_INT;
618
619    final Context mContext;
620    final boolean mFactoryTest;
621    final boolean mOnlyCore;
622    final DisplayMetrics mMetrics;
623    final int mDefParseFlags;
624    final String[] mSeparateProcesses;
625    final boolean mIsUpgrade;
626    final boolean mIsPreNUpgrade;
627    final boolean mIsPreNMR1Upgrade;
628
629    // Have we told the Activity Manager to whitelist the default container service by uid yet?
630    @GuardedBy("mPackages")
631    boolean mDefaultContainerWhitelisted = false;
632
633    @GuardedBy("mPackages")
634    private boolean mDexOptDialogShown;
635
636    /** The location for ASEC container files on internal storage. */
637    final String mAsecInternalPath;
638
639    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
640    // LOCK HELD.  Can be called with mInstallLock held.
641    @GuardedBy("mInstallLock")
642    final Installer mInstaller;
643
644    /** Directory where installed third-party apps stored */
645    final File mAppInstallDir;
646
647    /**
648     * Directory to which applications installed internally have their
649     * 32 bit native libraries copied.
650     */
651    private File mAppLib32InstallDir;
652
653    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
654    // apps.
655    final File mDrmAppPrivateInstallDir;
656
657    // ----------------------------------------------------------------
658
659    // Lock for state used when installing and doing other long running
660    // operations.  Methods that must be called with this lock held have
661    // the suffix "LI".
662    final Object mInstallLock = new Object();
663
664    // ----------------------------------------------------------------
665
666    // Keys are String (package name), values are Package.  This also serves
667    // as the lock for the global state.  Methods that must be called with
668    // this lock held have the prefix "LP".
669    @GuardedBy("mPackages")
670    final ArrayMap<String, PackageParser.Package> mPackages =
671            new ArrayMap<String, PackageParser.Package>();
672
673    final ArrayMap<String, Set<String>> mKnownCodebase =
674            new ArrayMap<String, Set<String>>();
675
676    // Keys are isolated uids and values are the uid of the application
677    // that created the isolated proccess.
678    @GuardedBy("mPackages")
679    final SparseIntArray mIsolatedOwners = new SparseIntArray();
680
681    /**
682     * Tracks new system packages [received in an OTA] that we expect to
683     * find updated user-installed versions. Keys are package name, values
684     * are package location.
685     */
686    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
687    /**
688     * Tracks high priority intent filters for protected actions. During boot, certain
689     * filter actions are protected and should never be allowed to have a high priority
690     * intent filter for them. However, there is one, and only one exception -- the
691     * setup wizard. It must be able to define a high priority intent filter for these
692     * actions to ensure there are no escapes from the wizard. We need to delay processing
693     * of these during boot as we need to look at all of the system packages in order
694     * to know which component is the setup wizard.
695     */
696    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
697    /**
698     * Whether or not processing protected filters should be deferred.
699     */
700    private boolean mDeferProtectedFilters = true;
701
702    /**
703     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
704     */
705    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
706    /**
707     * Whether or not system app permissions should be promoted from install to runtime.
708     */
709    boolean mPromoteSystemApps;
710
711    @GuardedBy("mPackages")
712    final Settings mSettings;
713
714    /**
715     * Set of package names that are currently "frozen", which means active
716     * surgery is being done on the code/data for that package. The platform
717     * will refuse to launch frozen packages to avoid race conditions.
718     *
719     * @see PackageFreezer
720     */
721    @GuardedBy("mPackages")
722    final ArraySet<String> mFrozenPackages = new ArraySet<>();
723
724    final ProtectedPackages mProtectedPackages;
725
726    boolean mFirstBoot;
727
728    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
729
730    // System configuration read by SystemConfig.
731    final int[] mGlobalGids;
732    final SparseArray<ArraySet<String>> mSystemPermissions;
733    @GuardedBy("mAvailableFeatures")
734    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
735
736    // If mac_permissions.xml was found for seinfo labeling.
737    boolean mFoundPolicyFile;
738
739    private final InstantAppRegistry mInstantAppRegistry;
740
741    @GuardedBy("mPackages")
742    int mChangedPackagesSequenceNumber;
743    /**
744     * List of changed [installed, removed or updated] packages.
745     * mapping from user id -> sequence number -> package name
746     */
747    @GuardedBy("mPackages")
748    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
749    /**
750     * The sequence number of the last change to a package.
751     * mapping from user id -> package name -> sequence number
752     */
753    @GuardedBy("mPackages")
754    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
755
756    class PackageParserCallback implements PackageParser.Callback {
757        @Override public final boolean hasFeature(String feature) {
758            return PackageManagerService.this.hasSystemFeature(feature, 0);
759        }
760
761        final List<PackageParser.Package> getStaticOverlayPackagesLocked(
762                Collection<PackageParser.Package> allPackages, String targetPackageName) {
763            List<PackageParser.Package> overlayPackages = null;
764            for (PackageParser.Package p : allPackages) {
765                if (targetPackageName.equals(p.mOverlayTarget) && p.mIsStaticOverlay) {
766                    if (overlayPackages == null) {
767                        overlayPackages = new ArrayList<PackageParser.Package>();
768                    }
769                    overlayPackages.add(p);
770                }
771            }
772            if (overlayPackages != null) {
773                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
774                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
775                        return p1.mOverlayPriority - p2.mOverlayPriority;
776                    }
777                };
778                Collections.sort(overlayPackages, cmp);
779            }
780            return overlayPackages;
781        }
782
783        final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages,
784                String targetPackageName, String targetPath) {
785            if ("android".equals(targetPackageName)) {
786                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
787                // native AssetManager.
788                return null;
789            }
790            List<PackageParser.Package> overlayPackages =
791                    getStaticOverlayPackagesLocked(allPackages, targetPackageName);
792            if (overlayPackages == null || overlayPackages.isEmpty()) {
793                return null;
794            }
795            List<String> overlayPathList = null;
796            for (PackageParser.Package overlayPackage : overlayPackages) {
797                if (targetPath == null) {
798                    if (overlayPathList == null) {
799                        overlayPathList = new ArrayList<String>();
800                    }
801                    overlayPathList.add(overlayPackage.baseCodePath);
802                    continue;
803                }
804
805                try {
806                    // Creates idmaps for system to parse correctly the Android manifest of the
807                    // target package.
808                    //
809                    // OverlayManagerService will update each of them with a correct gid from its
810                    // target package app id.
811                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
812                            UserHandle.getSharedAppGid(
813                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
814                    if (overlayPathList == null) {
815                        overlayPathList = new ArrayList<String>();
816                    }
817                    overlayPathList.add(overlayPackage.baseCodePath);
818                } catch (InstallerException e) {
819                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
820                            overlayPackage.baseCodePath);
821                }
822            }
823            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
824        }
825
826        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
827            synchronized (mPackages) {
828                return getStaticOverlayPathsLocked(
829                        mPackages.values(), targetPackageName, targetPath);
830            }
831        }
832
833        @Override public final String[] getOverlayApks(String targetPackageName) {
834            return getStaticOverlayPaths(targetPackageName, null);
835        }
836
837        @Override public final String[] getOverlayPaths(String targetPackageName,
838                String targetPath) {
839            return getStaticOverlayPaths(targetPackageName, targetPath);
840        }
841    };
842
843    class ParallelPackageParserCallback extends PackageParserCallback {
844        List<PackageParser.Package> mOverlayPackages = null;
845
846        void findStaticOverlayPackages() {
847            synchronized (mPackages) {
848                for (PackageParser.Package p : mPackages.values()) {
849                    if (p.mIsStaticOverlay) {
850                        if (mOverlayPackages == null) {
851                            mOverlayPackages = new ArrayList<PackageParser.Package>();
852                        }
853                        mOverlayPackages.add(p);
854                    }
855                }
856            }
857        }
858
859        @Override
860        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
861            // We can trust mOverlayPackages without holding mPackages because package uninstall
862            // can't happen while running parallel parsing.
863            // Moreover holding mPackages on each parsing thread causes dead-lock.
864            return mOverlayPackages == null ? null :
865                    getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath);
866        }
867    }
868
869    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
870    final ParallelPackageParserCallback mParallelPackageParserCallback =
871            new ParallelPackageParserCallback();
872
873    public static final class SharedLibraryEntry {
874        public final @Nullable String path;
875        public final @Nullable String apk;
876        public final @NonNull SharedLibraryInfo info;
877
878        SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
879                String declaringPackageName, int declaringPackageVersionCode) {
880            path = _path;
881            apk = _apk;
882            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
883                    declaringPackageName, declaringPackageVersionCode), null);
884        }
885    }
886
887    // Currently known shared libraries.
888    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
889    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
890            new ArrayMap<>();
891
892    // All available activities, for your resolving pleasure.
893    final ActivityIntentResolver mActivities =
894            new ActivityIntentResolver();
895
896    // All available receivers, for your resolving pleasure.
897    final ActivityIntentResolver mReceivers =
898            new ActivityIntentResolver();
899
900    // All available services, for your resolving pleasure.
901    final ServiceIntentResolver mServices = new ServiceIntentResolver();
902
903    // All available providers, for your resolving pleasure.
904    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
905
906    // Mapping from provider base names (first directory in content URI codePath)
907    // to the provider information.
908    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
909            new ArrayMap<String, PackageParser.Provider>();
910
911    // Mapping from instrumentation class names to info about them.
912    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
913            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
914
915    // Mapping from permission names to info about them.
916    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
917            new ArrayMap<String, PackageParser.PermissionGroup>();
918
919    // Packages whose data we have transfered into another package, thus
920    // should no longer exist.
921    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
922
923    // Broadcast actions that are only available to the system.
924    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
925
926    /** List of packages waiting for verification. */
927    final SparseArray<PackageVerificationState> mPendingVerification
928            = new SparseArray<PackageVerificationState>();
929
930    /** Set of packages associated with each app op permission. */
931    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
932
933    final PackageInstallerService mInstallerService;
934
935    private final PackageDexOptimizer mPackageDexOptimizer;
936    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
937    // is used by other apps).
938    private final DexManager mDexManager;
939
940    private AtomicInteger mNextMoveId = new AtomicInteger();
941    private final MoveCallbacks mMoveCallbacks;
942
943    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
944
945    // Cache of users who need badging.
946    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
947
948    /** Token for keys in mPendingVerification. */
949    private int mPendingVerificationToken = 0;
950
951    volatile boolean mSystemReady;
952    volatile boolean mSafeMode;
953    volatile boolean mHasSystemUidErrors;
954    private volatile boolean mEphemeralAppsDisabled;
955
956    ApplicationInfo mAndroidApplication;
957    final ActivityInfo mResolveActivity = new ActivityInfo();
958    final ResolveInfo mResolveInfo = new ResolveInfo();
959    ComponentName mResolveComponentName;
960    PackageParser.Package mPlatformPackage;
961    ComponentName mCustomResolverComponentName;
962
963    boolean mResolverReplaced = false;
964
965    private final @Nullable ComponentName mIntentFilterVerifierComponent;
966    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
967
968    private int mIntentFilterVerificationToken = 0;
969
970    /** The service connection to the ephemeral resolver */
971    final EphemeralResolverConnection mInstantAppResolverConnection;
972    /** Component used to show resolver settings for Instant Apps */
973    final ComponentName mInstantAppResolverSettingsComponent;
974
975    /** Activity used to install instant applications */
976    ActivityInfo mInstantAppInstallerActivity;
977    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
978
979    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
980            = new SparseArray<IntentFilterVerificationState>();
981
982    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
983
984    // List of packages names to keep cached, even if they are uninstalled for all users
985    private List<String> mKeepUninstalledPackages;
986
987    private UserManagerInternal mUserManagerInternal;
988
989    private DeviceIdleController.LocalService mDeviceIdleController;
990
991    private File mCacheDir;
992
993    private ArraySet<String> mPrivappPermissionsViolations;
994
995    private Future<?> mPrepareAppDataFuture;
996
997    private static class IFVerificationParams {
998        PackageParser.Package pkg;
999        boolean replacing;
1000        int userId;
1001        int verifierUid;
1002
1003        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1004                int _userId, int _verifierUid) {
1005            pkg = _pkg;
1006            replacing = _replacing;
1007            userId = _userId;
1008            replacing = _replacing;
1009            verifierUid = _verifierUid;
1010        }
1011    }
1012
1013    private interface IntentFilterVerifier<T extends IntentFilter> {
1014        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1015                                               T filter, String packageName);
1016        void startVerifications(int userId);
1017        void receiveVerificationResponse(int verificationId);
1018    }
1019
1020    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1021        private Context mContext;
1022        private ComponentName mIntentFilterVerifierComponent;
1023        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1024
1025        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1026            mContext = context;
1027            mIntentFilterVerifierComponent = verifierComponent;
1028        }
1029
1030        private String getDefaultScheme() {
1031            return IntentFilter.SCHEME_HTTPS;
1032        }
1033
1034        @Override
1035        public void startVerifications(int userId) {
1036            // Launch verifications requests
1037            int count = mCurrentIntentFilterVerifications.size();
1038            for (int n=0; n<count; n++) {
1039                int verificationId = mCurrentIntentFilterVerifications.get(n);
1040                final IntentFilterVerificationState ivs =
1041                        mIntentFilterVerificationStates.get(verificationId);
1042
1043                String packageName = ivs.getPackageName();
1044
1045                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1046                final int filterCount = filters.size();
1047                ArraySet<String> domainsSet = new ArraySet<>();
1048                for (int m=0; m<filterCount; m++) {
1049                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1050                    domainsSet.addAll(filter.getHostsList());
1051                }
1052                synchronized (mPackages) {
1053                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1054                            packageName, domainsSet) != null) {
1055                        scheduleWriteSettingsLocked();
1056                    }
1057                }
1058                sendVerificationRequest(userId, verificationId, ivs);
1059            }
1060            mCurrentIntentFilterVerifications.clear();
1061        }
1062
1063        private void sendVerificationRequest(int userId, int verificationId,
1064                IntentFilterVerificationState ivs) {
1065
1066            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1067            verificationIntent.putExtra(
1068                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1069                    verificationId);
1070            verificationIntent.putExtra(
1071                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1072                    getDefaultScheme());
1073            verificationIntent.putExtra(
1074                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1075                    ivs.getHostsString());
1076            verificationIntent.putExtra(
1077                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1078                    ivs.getPackageName());
1079            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1080            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1081
1082            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1083            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1084                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1085                    userId, false, "intent filter verifier");
1086
1087            UserHandle user = new UserHandle(userId);
1088            mContext.sendBroadcastAsUser(verificationIntent, user);
1089            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1090                    "Sending IntentFilter verification broadcast");
1091        }
1092
1093        public void receiveVerificationResponse(int verificationId) {
1094            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1095
1096            final boolean verified = ivs.isVerified();
1097
1098            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1099            final int count = filters.size();
1100            if (DEBUG_DOMAIN_VERIFICATION) {
1101                Slog.i(TAG, "Received verification response " + verificationId
1102                        + " for " + count + " filters, verified=" + verified);
1103            }
1104            for (int n=0; n<count; n++) {
1105                PackageParser.ActivityIntentInfo filter = filters.get(n);
1106                filter.setVerified(verified);
1107
1108                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1109                        + " verified with result:" + verified + " and hosts:"
1110                        + ivs.getHostsString());
1111            }
1112
1113            mIntentFilterVerificationStates.remove(verificationId);
1114
1115            final String packageName = ivs.getPackageName();
1116            IntentFilterVerificationInfo ivi = null;
1117
1118            synchronized (mPackages) {
1119                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1120            }
1121            if (ivi == null) {
1122                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1123                        + verificationId + " packageName:" + packageName);
1124                return;
1125            }
1126            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1127                    "Updating IntentFilterVerificationInfo for package " + packageName
1128                            +" verificationId:" + verificationId);
1129
1130            synchronized (mPackages) {
1131                if (verified) {
1132                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1133                } else {
1134                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1135                }
1136                scheduleWriteSettingsLocked();
1137
1138                final int userId = ivs.getUserId();
1139                if (userId != UserHandle.USER_ALL) {
1140                    final int userStatus =
1141                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1142
1143                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1144                    boolean needUpdate = false;
1145
1146                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1147                    // already been set by the User thru the Disambiguation dialog
1148                    switch (userStatus) {
1149                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1150                            if (verified) {
1151                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1152                            } else {
1153                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1154                            }
1155                            needUpdate = true;
1156                            break;
1157
1158                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1159                            if (verified) {
1160                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1161                                needUpdate = true;
1162                            }
1163                            break;
1164
1165                        default:
1166                            // Nothing to do
1167                    }
1168
1169                    if (needUpdate) {
1170                        mSettings.updateIntentFilterVerificationStatusLPw(
1171                                packageName, updatedStatus, userId);
1172                        scheduleWritePackageRestrictionsLocked(userId);
1173                    }
1174                }
1175            }
1176        }
1177
1178        @Override
1179        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1180                    ActivityIntentInfo filter, String packageName) {
1181            if (!hasValidDomains(filter)) {
1182                return false;
1183            }
1184            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1185            if (ivs == null) {
1186                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1187                        packageName);
1188            }
1189            if (DEBUG_DOMAIN_VERIFICATION) {
1190                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1191            }
1192            ivs.addFilter(filter);
1193            return true;
1194        }
1195
1196        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1197                int userId, int verificationId, String packageName) {
1198            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1199                    verifierUid, userId, packageName);
1200            ivs.setPendingState();
1201            synchronized (mPackages) {
1202                mIntentFilterVerificationStates.append(verificationId, ivs);
1203                mCurrentIntentFilterVerifications.add(verificationId);
1204            }
1205            return ivs;
1206        }
1207    }
1208
1209    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1210        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1211                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1212                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1213    }
1214
1215    // Set of pending broadcasts for aggregating enable/disable of components.
1216    static class PendingPackageBroadcasts {
1217        // for each user id, a map of <package name -> components within that package>
1218        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1219
1220        public PendingPackageBroadcasts() {
1221            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1222        }
1223
1224        public ArrayList<String> get(int userId, String packageName) {
1225            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1226            return packages.get(packageName);
1227        }
1228
1229        public void put(int userId, String packageName, ArrayList<String> components) {
1230            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1231            packages.put(packageName, components);
1232        }
1233
1234        public void remove(int userId, String packageName) {
1235            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1236            if (packages != null) {
1237                packages.remove(packageName);
1238            }
1239        }
1240
1241        public void remove(int userId) {
1242            mUidMap.remove(userId);
1243        }
1244
1245        public int userIdCount() {
1246            return mUidMap.size();
1247        }
1248
1249        public int userIdAt(int n) {
1250            return mUidMap.keyAt(n);
1251        }
1252
1253        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1254            return mUidMap.get(userId);
1255        }
1256
1257        public int size() {
1258            // total number of pending broadcast entries across all userIds
1259            int num = 0;
1260            for (int i = 0; i< mUidMap.size(); i++) {
1261                num += mUidMap.valueAt(i).size();
1262            }
1263            return num;
1264        }
1265
1266        public void clear() {
1267            mUidMap.clear();
1268        }
1269
1270        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1271            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1272            if (map == null) {
1273                map = new ArrayMap<String, ArrayList<String>>();
1274                mUidMap.put(userId, map);
1275            }
1276            return map;
1277        }
1278    }
1279    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1280
1281    // Service Connection to remote media container service to copy
1282    // package uri's from external media onto secure containers
1283    // or internal storage.
1284    private IMediaContainerService mContainerService = null;
1285
1286    static final int SEND_PENDING_BROADCAST = 1;
1287    static final int MCS_BOUND = 3;
1288    static final int END_COPY = 4;
1289    static final int INIT_COPY = 5;
1290    static final int MCS_UNBIND = 6;
1291    static final int START_CLEANING_PACKAGE = 7;
1292    static final int FIND_INSTALL_LOC = 8;
1293    static final int POST_INSTALL = 9;
1294    static final int MCS_RECONNECT = 10;
1295    static final int MCS_GIVE_UP = 11;
1296    static final int UPDATED_MEDIA_STATUS = 12;
1297    static final int WRITE_SETTINGS = 13;
1298    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1299    static final int PACKAGE_VERIFIED = 15;
1300    static final int CHECK_PENDING_VERIFICATION = 16;
1301    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1302    static final int INTENT_FILTER_VERIFIED = 18;
1303    static final int WRITE_PACKAGE_LIST = 19;
1304    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1305
1306    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1307
1308    // Delay time in millisecs
1309    static final int BROADCAST_DELAY = 10 * 1000;
1310
1311    private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1312            2 * 60 * 60 * 1000L; /* two hours */
1313
1314    static UserManagerService sUserManager;
1315
1316    // Stores a list of users whose package restrictions file needs to be updated
1317    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1318
1319    final private DefaultContainerConnection mDefContainerConn =
1320            new DefaultContainerConnection();
1321    class DefaultContainerConnection implements ServiceConnection {
1322        public void onServiceConnected(ComponentName name, IBinder service) {
1323            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1324            final IMediaContainerService imcs = IMediaContainerService.Stub
1325                    .asInterface(Binder.allowBlocking(service));
1326            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1327        }
1328
1329        public void onServiceDisconnected(ComponentName name) {
1330            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1331        }
1332    }
1333
1334    // Recordkeeping of restore-after-install operations that are currently in flight
1335    // between the Package Manager and the Backup Manager
1336    static class PostInstallData {
1337        public InstallArgs args;
1338        public PackageInstalledInfo res;
1339
1340        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1341            args = _a;
1342            res = _r;
1343        }
1344    }
1345
1346    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1347    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1348
1349    // XML tags for backup/restore of various bits of state
1350    private static final String TAG_PREFERRED_BACKUP = "pa";
1351    private static final String TAG_DEFAULT_APPS = "da";
1352    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1353
1354    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1355    private static final String TAG_ALL_GRANTS = "rt-grants";
1356    private static final String TAG_GRANT = "grant";
1357    private static final String ATTR_PACKAGE_NAME = "pkg";
1358
1359    private static final String TAG_PERMISSION = "perm";
1360    private static final String ATTR_PERMISSION_NAME = "name";
1361    private static final String ATTR_IS_GRANTED = "g";
1362    private static final String ATTR_USER_SET = "set";
1363    private static final String ATTR_USER_FIXED = "fixed";
1364    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1365
1366    // System/policy permission grants are not backed up
1367    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1368            FLAG_PERMISSION_POLICY_FIXED
1369            | FLAG_PERMISSION_SYSTEM_FIXED
1370            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1371
1372    // And we back up these user-adjusted states
1373    private static final int USER_RUNTIME_GRANT_MASK =
1374            FLAG_PERMISSION_USER_SET
1375            | FLAG_PERMISSION_USER_FIXED
1376            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1377
1378    final @Nullable String mRequiredVerifierPackage;
1379    final @NonNull String mRequiredInstallerPackage;
1380    final @NonNull String mRequiredUninstallerPackage;
1381    final @Nullable String mSetupWizardPackage;
1382    final @Nullable String mStorageManagerPackage;
1383    final @NonNull String mServicesSystemSharedLibraryPackageName;
1384    final @NonNull String mSharedSystemSharedLibraryPackageName;
1385
1386    final boolean mPermissionReviewRequired;
1387
1388    private final PackageUsage mPackageUsage = new PackageUsage();
1389    private final CompilerStats mCompilerStats = new CompilerStats();
1390
1391    class PackageHandler extends Handler {
1392        private boolean mBound = false;
1393        final ArrayList<HandlerParams> mPendingInstalls =
1394            new ArrayList<HandlerParams>();
1395
1396        private boolean connectToService() {
1397            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1398                    " DefaultContainerService");
1399            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1400            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1401            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1402                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1403                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1404                mBound = true;
1405                return true;
1406            }
1407            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1408            return false;
1409        }
1410
1411        private void disconnectService() {
1412            mContainerService = null;
1413            mBound = false;
1414            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1415            mContext.unbindService(mDefContainerConn);
1416            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1417        }
1418
1419        PackageHandler(Looper looper) {
1420            super(looper);
1421        }
1422
1423        public void handleMessage(Message msg) {
1424            try {
1425                doHandleMessage(msg);
1426            } finally {
1427                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1428            }
1429        }
1430
1431        void doHandleMessage(Message msg) {
1432            switch (msg.what) {
1433                case INIT_COPY: {
1434                    HandlerParams params = (HandlerParams) msg.obj;
1435                    int idx = mPendingInstalls.size();
1436                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1437                    // If a bind was already initiated we dont really
1438                    // need to do anything. The pending install
1439                    // will be processed later on.
1440                    if (!mBound) {
1441                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1442                                System.identityHashCode(mHandler));
1443                        // If this is the only one pending we might
1444                        // have to bind to the service again.
1445                        if (!connectToService()) {
1446                            Slog.e(TAG, "Failed to bind to media container service");
1447                            params.serviceError();
1448                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1449                                    System.identityHashCode(mHandler));
1450                            if (params.traceMethod != null) {
1451                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1452                                        params.traceCookie);
1453                            }
1454                            return;
1455                        } else {
1456                            // Once we bind to the service, the first
1457                            // pending request will be processed.
1458                            mPendingInstalls.add(idx, params);
1459                        }
1460                    } else {
1461                        mPendingInstalls.add(idx, params);
1462                        // Already bound to the service. Just make
1463                        // sure we trigger off processing the first request.
1464                        if (idx == 0) {
1465                            mHandler.sendEmptyMessage(MCS_BOUND);
1466                        }
1467                    }
1468                    break;
1469                }
1470                case MCS_BOUND: {
1471                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1472                    if (msg.obj != null) {
1473                        mContainerService = (IMediaContainerService) msg.obj;
1474                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1475                                System.identityHashCode(mHandler));
1476                    }
1477                    if (mContainerService == null) {
1478                        if (!mBound) {
1479                            // Something seriously wrong since we are not bound and we are not
1480                            // waiting for connection. Bail out.
1481                            Slog.e(TAG, "Cannot bind to media container service");
1482                            for (HandlerParams params : mPendingInstalls) {
1483                                // Indicate service bind error
1484                                params.serviceError();
1485                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1486                                        System.identityHashCode(params));
1487                                if (params.traceMethod != null) {
1488                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1489                                            params.traceMethod, params.traceCookie);
1490                                }
1491                                return;
1492                            }
1493                            mPendingInstalls.clear();
1494                        } else {
1495                            Slog.w(TAG, "Waiting to connect to media container service");
1496                        }
1497                    } else if (mPendingInstalls.size() > 0) {
1498                        HandlerParams params = mPendingInstalls.get(0);
1499                        if (params != null) {
1500                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1501                                    System.identityHashCode(params));
1502                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1503                            if (params.startCopy()) {
1504                                // We are done...  look for more work or to
1505                                // go idle.
1506                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1507                                        "Checking for more work or unbind...");
1508                                // Delete pending install
1509                                if (mPendingInstalls.size() > 0) {
1510                                    mPendingInstalls.remove(0);
1511                                }
1512                                if (mPendingInstalls.size() == 0) {
1513                                    if (mBound) {
1514                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1515                                                "Posting delayed MCS_UNBIND");
1516                                        removeMessages(MCS_UNBIND);
1517                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1518                                        // Unbind after a little delay, to avoid
1519                                        // continual thrashing.
1520                                        sendMessageDelayed(ubmsg, 10000);
1521                                    }
1522                                } else {
1523                                    // There are more pending requests in queue.
1524                                    // Just post MCS_BOUND message to trigger processing
1525                                    // of next pending install.
1526                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1527                                            "Posting MCS_BOUND for next work");
1528                                    mHandler.sendEmptyMessage(MCS_BOUND);
1529                                }
1530                            }
1531                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1532                        }
1533                    } else {
1534                        // Should never happen ideally.
1535                        Slog.w(TAG, "Empty queue");
1536                    }
1537                    break;
1538                }
1539                case MCS_RECONNECT: {
1540                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1541                    if (mPendingInstalls.size() > 0) {
1542                        if (mBound) {
1543                            disconnectService();
1544                        }
1545                        if (!connectToService()) {
1546                            Slog.e(TAG, "Failed to bind to media container service");
1547                            for (HandlerParams params : mPendingInstalls) {
1548                                // Indicate service bind error
1549                                params.serviceError();
1550                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1551                                        System.identityHashCode(params));
1552                            }
1553                            mPendingInstalls.clear();
1554                        }
1555                    }
1556                    break;
1557                }
1558                case MCS_UNBIND: {
1559                    // If there is no actual work left, then time to unbind.
1560                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1561
1562                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1563                        if (mBound) {
1564                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1565
1566                            disconnectService();
1567                        }
1568                    } else if (mPendingInstalls.size() > 0) {
1569                        // There are more pending requests in queue.
1570                        // Just post MCS_BOUND message to trigger processing
1571                        // of next pending install.
1572                        mHandler.sendEmptyMessage(MCS_BOUND);
1573                    }
1574
1575                    break;
1576                }
1577                case MCS_GIVE_UP: {
1578                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1579                    HandlerParams params = mPendingInstalls.remove(0);
1580                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1581                            System.identityHashCode(params));
1582                    break;
1583                }
1584                case SEND_PENDING_BROADCAST: {
1585                    String packages[];
1586                    ArrayList<String> components[];
1587                    int size = 0;
1588                    int uids[];
1589                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1590                    synchronized (mPackages) {
1591                        if (mPendingBroadcasts == null) {
1592                            return;
1593                        }
1594                        size = mPendingBroadcasts.size();
1595                        if (size <= 0) {
1596                            // Nothing to be done. Just return
1597                            return;
1598                        }
1599                        packages = new String[size];
1600                        components = new ArrayList[size];
1601                        uids = new int[size];
1602                        int i = 0;  // filling out the above arrays
1603
1604                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1605                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1606                            Iterator<Map.Entry<String, ArrayList<String>>> it
1607                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1608                                            .entrySet().iterator();
1609                            while (it.hasNext() && i < size) {
1610                                Map.Entry<String, ArrayList<String>> ent = it.next();
1611                                packages[i] = ent.getKey();
1612                                components[i] = ent.getValue();
1613                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1614                                uids[i] = (ps != null)
1615                                        ? UserHandle.getUid(packageUserId, ps.appId)
1616                                        : -1;
1617                                i++;
1618                            }
1619                        }
1620                        size = i;
1621                        mPendingBroadcasts.clear();
1622                    }
1623                    // Send broadcasts
1624                    for (int i = 0; i < size; i++) {
1625                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1626                    }
1627                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1628                    break;
1629                }
1630                case START_CLEANING_PACKAGE: {
1631                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1632                    final String packageName = (String)msg.obj;
1633                    final int userId = msg.arg1;
1634                    final boolean andCode = msg.arg2 != 0;
1635                    synchronized (mPackages) {
1636                        if (userId == UserHandle.USER_ALL) {
1637                            int[] users = sUserManager.getUserIds();
1638                            for (int user : users) {
1639                                mSettings.addPackageToCleanLPw(
1640                                        new PackageCleanItem(user, packageName, andCode));
1641                            }
1642                        } else {
1643                            mSettings.addPackageToCleanLPw(
1644                                    new PackageCleanItem(userId, packageName, andCode));
1645                        }
1646                    }
1647                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1648                    startCleaningPackages();
1649                } break;
1650                case POST_INSTALL: {
1651                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1652
1653                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1654                    final boolean didRestore = (msg.arg2 != 0);
1655                    mRunningInstalls.delete(msg.arg1);
1656
1657                    if (data != null) {
1658                        InstallArgs args = data.args;
1659                        PackageInstalledInfo parentRes = data.res;
1660
1661                        final boolean grantPermissions = (args.installFlags
1662                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1663                        final boolean killApp = (args.installFlags
1664                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1665                        final String[] grantedPermissions = args.installGrantPermissions;
1666
1667                        // Handle the parent package
1668                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1669                                grantedPermissions, didRestore, args.installerPackageName,
1670                                args.observer);
1671
1672                        // Handle the child packages
1673                        final int childCount = (parentRes.addedChildPackages != null)
1674                                ? parentRes.addedChildPackages.size() : 0;
1675                        for (int i = 0; i < childCount; i++) {
1676                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1677                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1678                                    grantedPermissions, false, args.installerPackageName,
1679                                    args.observer);
1680                        }
1681
1682                        // Log tracing if needed
1683                        if (args.traceMethod != null) {
1684                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1685                                    args.traceCookie);
1686                        }
1687                    } else {
1688                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1689                    }
1690
1691                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1692                } break;
1693                case UPDATED_MEDIA_STATUS: {
1694                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1695                    boolean reportStatus = msg.arg1 == 1;
1696                    boolean doGc = msg.arg2 == 1;
1697                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1698                    if (doGc) {
1699                        // Force a gc to clear up stale containers.
1700                        Runtime.getRuntime().gc();
1701                    }
1702                    if (msg.obj != null) {
1703                        @SuppressWarnings("unchecked")
1704                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1705                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1706                        // Unload containers
1707                        unloadAllContainers(args);
1708                    }
1709                    if (reportStatus) {
1710                        try {
1711                            if (DEBUG_SD_INSTALL) Log.i(TAG,
1712                                    "Invoking StorageManagerService call back");
1713                            PackageHelper.getStorageManager().finishMediaUpdate();
1714                        } catch (RemoteException e) {
1715                            Log.e(TAG, "StorageManagerService not running?");
1716                        }
1717                    }
1718                } break;
1719                case WRITE_SETTINGS: {
1720                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1721                    synchronized (mPackages) {
1722                        removeMessages(WRITE_SETTINGS);
1723                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1724                        mSettings.writeLPr();
1725                        mDirtyUsers.clear();
1726                    }
1727                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1728                } break;
1729                case WRITE_PACKAGE_RESTRICTIONS: {
1730                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1731                    synchronized (mPackages) {
1732                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1733                        for (int userId : mDirtyUsers) {
1734                            mSettings.writePackageRestrictionsLPr(userId);
1735                        }
1736                        mDirtyUsers.clear();
1737                    }
1738                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1739                } break;
1740                case WRITE_PACKAGE_LIST: {
1741                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1742                    synchronized (mPackages) {
1743                        removeMessages(WRITE_PACKAGE_LIST);
1744                        mSettings.writePackageListLPr(msg.arg1);
1745                    }
1746                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1747                } break;
1748                case CHECK_PENDING_VERIFICATION: {
1749                    final int verificationId = msg.arg1;
1750                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1751
1752                    if ((state != null) && !state.timeoutExtended()) {
1753                        final InstallArgs args = state.getInstallArgs();
1754                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1755
1756                        Slog.i(TAG, "Verification timed out for " + originUri);
1757                        mPendingVerification.remove(verificationId);
1758
1759                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1760
1761                        final UserHandle user = args.getUser();
1762                        if (getDefaultVerificationResponse(user)
1763                                == PackageManager.VERIFICATION_ALLOW) {
1764                            Slog.i(TAG, "Continuing with installation of " + originUri);
1765                            state.setVerifierResponse(Binder.getCallingUid(),
1766                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1767                            broadcastPackageVerified(verificationId, originUri,
1768                                    PackageManager.VERIFICATION_ALLOW, user);
1769                            try {
1770                                ret = args.copyApk(mContainerService, true);
1771                            } catch (RemoteException e) {
1772                                Slog.e(TAG, "Could not contact the ContainerService");
1773                            }
1774                        } else {
1775                            broadcastPackageVerified(verificationId, originUri,
1776                                    PackageManager.VERIFICATION_REJECT, user);
1777                        }
1778
1779                        Trace.asyncTraceEnd(
1780                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1781
1782                        processPendingInstall(args, ret);
1783                        mHandler.sendEmptyMessage(MCS_UNBIND);
1784                    }
1785                    break;
1786                }
1787                case PACKAGE_VERIFIED: {
1788                    final int verificationId = msg.arg1;
1789
1790                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1791                    if (state == null) {
1792                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1793                        break;
1794                    }
1795
1796                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1797
1798                    state.setVerifierResponse(response.callerUid, response.code);
1799
1800                    if (state.isVerificationComplete()) {
1801                        mPendingVerification.remove(verificationId);
1802
1803                        final InstallArgs args = state.getInstallArgs();
1804                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1805
1806                        int ret;
1807                        if (state.isInstallAllowed()) {
1808                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1809                            broadcastPackageVerified(verificationId, originUri,
1810                                    response.code, state.getInstallArgs().getUser());
1811                            try {
1812                                ret = args.copyApk(mContainerService, true);
1813                            } catch (RemoteException e) {
1814                                Slog.e(TAG, "Could not contact the ContainerService");
1815                            }
1816                        } else {
1817                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1818                        }
1819
1820                        Trace.asyncTraceEnd(
1821                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1822
1823                        processPendingInstall(args, ret);
1824                        mHandler.sendEmptyMessage(MCS_UNBIND);
1825                    }
1826
1827                    break;
1828                }
1829                case START_INTENT_FILTER_VERIFICATIONS: {
1830                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1831                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1832                            params.replacing, params.pkg);
1833                    break;
1834                }
1835                case INTENT_FILTER_VERIFIED: {
1836                    final int verificationId = msg.arg1;
1837
1838                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1839                            verificationId);
1840                    if (state == null) {
1841                        Slog.w(TAG, "Invalid IntentFilter verification token "
1842                                + verificationId + " received");
1843                        break;
1844                    }
1845
1846                    final int userId = state.getUserId();
1847
1848                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1849                            "Processing IntentFilter verification with token:"
1850                            + verificationId + " and userId:" + userId);
1851
1852                    final IntentFilterVerificationResponse response =
1853                            (IntentFilterVerificationResponse) msg.obj;
1854
1855                    state.setVerifierResponse(response.callerUid, response.code);
1856
1857                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1858                            "IntentFilter verification with token:" + verificationId
1859                            + " and userId:" + userId
1860                            + " is settings verifier response with response code:"
1861                            + response.code);
1862
1863                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1864                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1865                                + response.getFailedDomainsString());
1866                    }
1867
1868                    if (state.isVerificationComplete()) {
1869                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1870                    } else {
1871                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1872                                "IntentFilter verification with token:" + verificationId
1873                                + " was not said to be complete");
1874                    }
1875
1876                    break;
1877                }
1878                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1879                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1880                            mInstantAppResolverConnection,
1881                            (InstantAppRequest) msg.obj,
1882                            mInstantAppInstallerActivity,
1883                            mHandler);
1884                }
1885            }
1886        }
1887    }
1888
1889    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1890            boolean killApp, String[] grantedPermissions,
1891            boolean launchedForRestore, String installerPackage,
1892            IPackageInstallObserver2 installObserver) {
1893        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1894            // Send the removed broadcasts
1895            if (res.removedInfo != null) {
1896                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1897            }
1898
1899            // Now that we successfully installed the package, grant runtime
1900            // permissions if requested before broadcasting the install. Also
1901            // for legacy apps in permission review mode we clear the permission
1902            // review flag which is used to emulate runtime permissions for
1903            // legacy apps.
1904            if (grantPermissions) {
1905                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1906            }
1907
1908            final boolean update = res.removedInfo != null
1909                    && res.removedInfo.removedPackage != null;
1910            final String origInstallerPackageName = res.removedInfo != null
1911                    ? res.removedInfo.installerPackageName : null;
1912
1913            // If this is the first time we have child packages for a disabled privileged
1914            // app that had no children, we grant requested runtime permissions to the new
1915            // children if the parent on the system image had them already granted.
1916            if (res.pkg.parentPackage != null) {
1917                synchronized (mPackages) {
1918                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1919                }
1920            }
1921
1922            synchronized (mPackages) {
1923                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1924            }
1925
1926            final String packageName = res.pkg.applicationInfo.packageName;
1927
1928            // Determine the set of users who are adding this package for
1929            // the first time vs. those who are seeing an update.
1930            int[] firstUsers = EMPTY_INT_ARRAY;
1931            int[] updateUsers = EMPTY_INT_ARRAY;
1932            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1933            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1934            for (int newUser : res.newUsers) {
1935                if (ps.getInstantApp(newUser)) {
1936                    continue;
1937                }
1938                if (allNewUsers) {
1939                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1940                    continue;
1941                }
1942                boolean isNew = true;
1943                for (int origUser : res.origUsers) {
1944                    if (origUser == newUser) {
1945                        isNew = false;
1946                        break;
1947                    }
1948                }
1949                if (isNew) {
1950                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1951                } else {
1952                    updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1953                }
1954            }
1955
1956            // Send installed broadcasts if the package is not a static shared lib.
1957            if (res.pkg.staticSharedLibName == null) {
1958                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1959
1960                // Send added for users that see the package for the first time
1961                // sendPackageAddedForNewUsers also deals with system apps
1962                int appId = UserHandle.getAppId(res.uid);
1963                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1964                sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers);
1965
1966                // Send added for users that don't see the package for the first time
1967                Bundle extras = new Bundle(1);
1968                extras.putInt(Intent.EXTRA_UID, res.uid);
1969                if (update) {
1970                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1971                }
1972                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1973                        extras, 0 /*flags*/,
1974                        null /*targetPackage*/, null /*finishedReceiver*/, updateUsers);
1975                if (origInstallerPackageName != null) {
1976                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1977                            extras, 0 /*flags*/,
1978                            origInstallerPackageName, null /*finishedReceiver*/, updateUsers);
1979                }
1980
1981                // Send replaced for users that don't see the package for the first time
1982                if (update) {
1983                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1984                            packageName, extras, 0 /*flags*/,
1985                            null /*targetPackage*/, null /*finishedReceiver*/,
1986                            updateUsers);
1987                    if (origInstallerPackageName != null) {
1988                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
1989                                extras, 0 /*flags*/,
1990                                origInstallerPackageName, null /*finishedReceiver*/, updateUsers);
1991                    }
1992                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1993                            null /*package*/, null /*extras*/, 0 /*flags*/,
1994                            packageName /*targetPackage*/,
1995                            null /*finishedReceiver*/, updateUsers);
1996                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1997                    // First-install and we did a restore, so we're responsible for the
1998                    // first-launch broadcast.
1999                    if (DEBUG_BACKUP) {
2000                        Slog.i(TAG, "Post-restore of " + packageName
2001                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
2002                    }
2003                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
2004                }
2005
2006                // Send broadcast package appeared if forward locked/external for all users
2007                // treat asec-hosted packages like removable media on upgrade
2008                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2009                    if (DEBUG_INSTALL) {
2010                        Slog.i(TAG, "upgrading pkg " + res.pkg
2011                                + " is ASEC-hosted -> AVAILABLE");
2012                    }
2013                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2014                    ArrayList<String> pkgList = new ArrayList<>(1);
2015                    pkgList.add(packageName);
2016                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2017                }
2018            }
2019
2020            // Work that needs to happen on first install within each user
2021            if (firstUsers != null && firstUsers.length > 0) {
2022                synchronized (mPackages) {
2023                    for (int userId : firstUsers) {
2024                        // If this app is a browser and it's newly-installed for some
2025                        // users, clear any default-browser state in those users. The
2026                        // app's nature doesn't depend on the user, so we can just check
2027                        // its browser nature in any user and generalize.
2028                        if (packageIsBrowser(packageName, userId)) {
2029                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2030                        }
2031
2032                        // We may also need to apply pending (restored) runtime
2033                        // permission grants within these users.
2034                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2035                    }
2036                }
2037            }
2038
2039            // Log current value of "unknown sources" setting
2040            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2041                    getUnknownSourcesSettings());
2042
2043            // Remove the replaced package's older resources safely now
2044            // We delete after a gc for applications  on sdcard.
2045            if (res.removedInfo != null && res.removedInfo.args != null) {
2046                Runtime.getRuntime().gc();
2047                synchronized (mInstallLock) {
2048                    res.removedInfo.args.doPostDeleteLI(true);
2049                }
2050            } else {
2051                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2052                // and not block here.
2053                VMRuntime.getRuntime().requestConcurrentGC();
2054            }
2055
2056            // Notify DexManager that the package was installed for new users.
2057            // The updated users should already be indexed and the package code paths
2058            // should not change.
2059            // Don't notify the manager for ephemeral apps as they are not expected to
2060            // survive long enough to benefit of background optimizations.
2061            for (int userId : firstUsers) {
2062                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2063                // There's a race currently where some install events may interleave with an uninstall.
2064                // This can lead to package info being null (b/36642664).
2065                if (info != null) {
2066                    mDexManager.notifyPackageInstalled(info, userId);
2067                }
2068            }
2069        }
2070
2071        // If someone is watching installs - notify them
2072        if (installObserver != null) {
2073            try {
2074                Bundle extras = extrasForInstallResult(res);
2075                installObserver.onPackageInstalled(res.name, res.returnCode,
2076                        res.returnMsg, extras);
2077            } catch (RemoteException e) {
2078                Slog.i(TAG, "Observer no longer exists.");
2079            }
2080        }
2081    }
2082
2083    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
2084            PackageParser.Package pkg) {
2085        if (pkg.parentPackage == null) {
2086            return;
2087        }
2088        if (pkg.requestedPermissions == null) {
2089            return;
2090        }
2091        final PackageSetting disabledSysParentPs = mSettings
2092                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
2093        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
2094                || !disabledSysParentPs.isPrivileged()
2095                || (disabledSysParentPs.childPackageNames != null
2096                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
2097            return;
2098        }
2099        final int[] allUserIds = sUserManager.getUserIds();
2100        final int permCount = pkg.requestedPermissions.size();
2101        for (int i = 0; i < permCount; i++) {
2102            String permission = pkg.requestedPermissions.get(i);
2103            BasePermission bp = mSettings.mPermissions.get(permission);
2104            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
2105                continue;
2106            }
2107            for (int userId : allUserIds) {
2108                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
2109                        permission, userId)) {
2110                    grantRuntimePermission(pkg.packageName, permission, userId);
2111                }
2112            }
2113        }
2114    }
2115
2116    private StorageEventListener mStorageListener = new StorageEventListener() {
2117        @Override
2118        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2119            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2120                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2121                    final String volumeUuid = vol.getFsUuid();
2122
2123                    // Clean up any users or apps that were removed or recreated
2124                    // while this volume was missing
2125                    sUserManager.reconcileUsers(volumeUuid);
2126                    reconcileApps(volumeUuid);
2127
2128                    // Clean up any install sessions that expired or were
2129                    // cancelled while this volume was missing
2130                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2131
2132                    loadPrivatePackages(vol);
2133
2134                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2135                    unloadPrivatePackages(vol);
2136                }
2137            }
2138
2139            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
2140                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2141                    updateExternalMediaStatus(true, false);
2142                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2143                    updateExternalMediaStatus(false, false);
2144                }
2145            }
2146        }
2147
2148        @Override
2149        public void onVolumeForgotten(String fsUuid) {
2150            if (TextUtils.isEmpty(fsUuid)) {
2151                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2152                return;
2153            }
2154
2155            // Remove any apps installed on the forgotten volume
2156            synchronized (mPackages) {
2157                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2158                for (PackageSetting ps : packages) {
2159                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2160                    deletePackageVersioned(new VersionedPackage(ps.name,
2161                            PackageManager.VERSION_CODE_HIGHEST),
2162                            new LegacyPackageDeleteObserver(null).getBinder(),
2163                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2164                    // Try very hard to release any references to this package
2165                    // so we don't risk the system server being killed due to
2166                    // open FDs
2167                    AttributeCache.instance().removePackage(ps.name);
2168                }
2169
2170                mSettings.onVolumeForgotten(fsUuid);
2171                mSettings.writeLPr();
2172            }
2173        }
2174    };
2175
2176    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2177            String[] grantedPermissions) {
2178        for (int userId : userIds) {
2179            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2180        }
2181    }
2182
2183    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2184            String[] grantedPermissions) {
2185        PackageSetting ps = (PackageSetting) pkg.mExtras;
2186        if (ps == null) {
2187            return;
2188        }
2189
2190        PermissionsState permissionsState = ps.getPermissionsState();
2191
2192        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2193                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2194
2195        final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
2196                >= Build.VERSION_CODES.M;
2197
2198        final boolean instantApp = isInstantApp(pkg.packageName, userId);
2199
2200        for (String permission : pkg.requestedPermissions) {
2201            final BasePermission bp;
2202            synchronized (mPackages) {
2203                bp = mSettings.mPermissions.get(permission);
2204            }
2205            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2206                    && (!instantApp || bp.isInstant())
2207                    && (supportsRuntimePermissions || !bp.isRuntimeOnly())
2208                    && (grantedPermissions == null
2209                           || ArrayUtils.contains(grantedPermissions, permission))) {
2210                final int flags = permissionsState.getPermissionFlags(permission, userId);
2211                if (supportsRuntimePermissions) {
2212                    // Installer cannot change immutable permissions.
2213                    if ((flags & immutableFlags) == 0) {
2214                        grantRuntimePermission(pkg.packageName, permission, userId);
2215                    }
2216                } else if (mPermissionReviewRequired) {
2217                    // In permission review mode we clear the review flag when we
2218                    // are asked to install the app with all permissions granted.
2219                    if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
2220                        updatePermissionFlags(permission, pkg.packageName,
2221                                PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId);
2222                    }
2223                }
2224            }
2225        }
2226    }
2227
2228    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2229        Bundle extras = null;
2230        switch (res.returnCode) {
2231            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2232                extras = new Bundle();
2233                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2234                        res.origPermission);
2235                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2236                        res.origPackage);
2237                break;
2238            }
2239            case PackageManager.INSTALL_SUCCEEDED: {
2240                extras = new Bundle();
2241                extras.putBoolean(Intent.EXTRA_REPLACING,
2242                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2243                break;
2244            }
2245        }
2246        return extras;
2247    }
2248
2249    void scheduleWriteSettingsLocked() {
2250        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2251            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2252        }
2253    }
2254
2255    void scheduleWritePackageListLocked(int userId) {
2256        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2257            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2258            msg.arg1 = userId;
2259            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2260        }
2261    }
2262
2263    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2264        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2265        scheduleWritePackageRestrictionsLocked(userId);
2266    }
2267
2268    void scheduleWritePackageRestrictionsLocked(int userId) {
2269        final int[] userIds = (userId == UserHandle.USER_ALL)
2270                ? sUserManager.getUserIds() : new int[]{userId};
2271        for (int nextUserId : userIds) {
2272            if (!sUserManager.exists(nextUserId)) return;
2273            mDirtyUsers.add(nextUserId);
2274            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2275                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2276            }
2277        }
2278    }
2279
2280    public static PackageManagerService main(Context context, Installer installer,
2281            boolean factoryTest, boolean onlyCore) {
2282        // Self-check for initial settings.
2283        PackageManagerServiceCompilerMapping.checkProperties();
2284
2285        PackageManagerService m = new PackageManagerService(context, installer,
2286                factoryTest, onlyCore);
2287        m.enableSystemUserPackages();
2288        ServiceManager.addService("package", m);
2289        return m;
2290    }
2291
2292    private void enableSystemUserPackages() {
2293        if (!UserManager.isSplitSystemUser()) {
2294            return;
2295        }
2296        // For system user, enable apps based on the following conditions:
2297        // - app is whitelisted or belong to one of these groups:
2298        //   -- system app which has no launcher icons
2299        //   -- system app which has INTERACT_ACROSS_USERS permission
2300        //   -- system IME app
2301        // - app is not in the blacklist
2302        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2303        Set<String> enableApps = new ArraySet<>();
2304        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2305                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2306                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2307        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2308        enableApps.addAll(wlApps);
2309        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2310                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2311        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2312        enableApps.removeAll(blApps);
2313        Log.i(TAG, "Applications installed for system user: " + enableApps);
2314        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2315                UserHandle.SYSTEM);
2316        final int allAppsSize = allAps.size();
2317        synchronized (mPackages) {
2318            for (int i = 0; i < allAppsSize; i++) {
2319                String pName = allAps.get(i);
2320                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2321                // Should not happen, but we shouldn't be failing if it does
2322                if (pkgSetting == null) {
2323                    continue;
2324                }
2325                boolean install = enableApps.contains(pName);
2326                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2327                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2328                            + " for system user");
2329                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2330                }
2331            }
2332            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2333        }
2334    }
2335
2336    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2337        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2338                Context.DISPLAY_SERVICE);
2339        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2340    }
2341
2342    /**
2343     * Requests that files preopted on a secondary system partition be copied to the data partition
2344     * if possible.  Note that the actual copying of the files is accomplished by init for security
2345     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2346     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2347     */
2348    private static void requestCopyPreoptedFiles() {
2349        final int WAIT_TIME_MS = 100;
2350        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2351        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2352            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2353            // We will wait for up to 100 seconds.
2354            final long timeStart = SystemClock.uptimeMillis();
2355            final long timeEnd = timeStart + 100 * 1000;
2356            long timeNow = timeStart;
2357            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2358                try {
2359                    Thread.sleep(WAIT_TIME_MS);
2360                } catch (InterruptedException e) {
2361                    // Do nothing
2362                }
2363                timeNow = SystemClock.uptimeMillis();
2364                if (timeNow > timeEnd) {
2365                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2366                    Slog.wtf(TAG, "cppreopt did not finish!");
2367                    break;
2368                }
2369            }
2370
2371            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2372        }
2373    }
2374
2375    public PackageManagerService(Context context, Installer installer,
2376            boolean factoryTest, boolean onlyCore) {
2377        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2378        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2379        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2380                SystemClock.uptimeMillis());
2381
2382        if (mSdkVersion <= 0) {
2383            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2384        }
2385
2386        mContext = context;
2387
2388        mPermissionReviewRequired = context.getResources().getBoolean(
2389                R.bool.config_permissionReviewRequired);
2390
2391        mFactoryTest = factoryTest;
2392        mOnlyCore = onlyCore;
2393        mMetrics = new DisplayMetrics();
2394        mSettings = new Settings(mPackages);
2395        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2396                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2397        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2398                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2399        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2400                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2401        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2402                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2403        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2404                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2405        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2406                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2407
2408        String separateProcesses = SystemProperties.get("debug.separate_processes");
2409        if (separateProcesses != null && separateProcesses.length() > 0) {
2410            if ("*".equals(separateProcesses)) {
2411                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2412                mSeparateProcesses = null;
2413                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2414            } else {
2415                mDefParseFlags = 0;
2416                mSeparateProcesses = separateProcesses.split(",");
2417                Slog.w(TAG, "Running with debug.separate_processes: "
2418                        + separateProcesses);
2419            }
2420        } else {
2421            mDefParseFlags = 0;
2422            mSeparateProcesses = null;
2423        }
2424
2425        mInstaller = installer;
2426        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2427                "*dexopt*");
2428        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
2429        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2430
2431        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2432                FgThread.get().getLooper());
2433
2434        getDefaultDisplayMetrics(context, mMetrics);
2435
2436        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2437        SystemConfig systemConfig = SystemConfig.getInstance();
2438        mGlobalGids = systemConfig.getGlobalGids();
2439        mSystemPermissions = systemConfig.getSystemPermissions();
2440        mAvailableFeatures = systemConfig.getAvailableFeatures();
2441        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2442
2443        mProtectedPackages = new ProtectedPackages(mContext);
2444
2445        synchronized (mInstallLock) {
2446        // writer
2447        synchronized (mPackages) {
2448            mHandlerThread = new ServiceThread(TAG,
2449                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2450            mHandlerThread.start();
2451            mHandler = new PackageHandler(mHandlerThread.getLooper());
2452            mProcessLoggingHandler = new ProcessLoggingHandler();
2453            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2454
2455            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2456            mInstantAppRegistry = new InstantAppRegistry(this);
2457
2458            File dataDir = Environment.getDataDirectory();
2459            mAppInstallDir = new File(dataDir, "app");
2460            mAppLib32InstallDir = new File(dataDir, "app-lib");
2461            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2462            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2463            sUserManager = new UserManagerService(context, this,
2464                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2465
2466            // Propagate permission configuration in to package manager.
2467            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2468                    = systemConfig.getPermissions();
2469            for (int i=0; i<permConfig.size(); i++) {
2470                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2471                BasePermission bp = mSettings.mPermissions.get(perm.name);
2472                if (bp == null) {
2473                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2474                    mSettings.mPermissions.put(perm.name, bp);
2475                }
2476                if (perm.gids != null) {
2477                    bp.setGids(perm.gids, perm.perUser);
2478                }
2479            }
2480
2481            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2482            final int builtInLibCount = libConfig.size();
2483            for (int i = 0; i < builtInLibCount; i++) {
2484                String name = libConfig.keyAt(i);
2485                String path = libConfig.valueAt(i);
2486                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2487                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2488            }
2489
2490            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2491
2492            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2493            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2494            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2495
2496            // Clean up orphaned packages for which the code path doesn't exist
2497            // and they are an update to a system app - caused by bug/32321269
2498            final int packageSettingCount = mSettings.mPackages.size();
2499            for (int i = packageSettingCount - 1; i >= 0; i--) {
2500                PackageSetting ps = mSettings.mPackages.valueAt(i);
2501                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2502                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2503                    mSettings.mPackages.removeAt(i);
2504                    mSettings.enableSystemPackageLPw(ps.name);
2505                }
2506            }
2507
2508            if (mFirstBoot) {
2509                requestCopyPreoptedFiles();
2510            }
2511
2512            String customResolverActivity = Resources.getSystem().getString(
2513                    R.string.config_customResolverActivity);
2514            if (TextUtils.isEmpty(customResolverActivity)) {
2515                customResolverActivity = null;
2516            } else {
2517                mCustomResolverComponentName = ComponentName.unflattenFromString(
2518                        customResolverActivity);
2519            }
2520
2521            long startTime = SystemClock.uptimeMillis();
2522
2523            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2524                    startTime);
2525
2526            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2527            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2528
2529            if (bootClassPath == null) {
2530                Slog.w(TAG, "No BOOTCLASSPATH found!");
2531            }
2532
2533            if (systemServerClassPath == null) {
2534                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2535            }
2536
2537            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2538
2539            final VersionInfo ver = mSettings.getInternalVersion();
2540            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2541            if (mIsUpgrade) {
2542                logCriticalInfo(Log.INFO,
2543                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2544            }
2545
2546            // when upgrading from pre-M, promote system app permissions from install to runtime
2547            mPromoteSystemApps =
2548                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2549
2550            // When upgrading from pre-N, we need to handle package extraction like first boot,
2551            // as there is no profiling data available.
2552            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2553
2554            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2555
2556            // save off the names of pre-existing system packages prior to scanning; we don't
2557            // want to automatically grant runtime permissions for new system apps
2558            if (mPromoteSystemApps) {
2559                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2560                while (pkgSettingIter.hasNext()) {
2561                    PackageSetting ps = pkgSettingIter.next();
2562                    if (isSystemApp(ps)) {
2563                        mExistingSystemPackages.add(ps.name);
2564                    }
2565                }
2566            }
2567
2568            mCacheDir = preparePackageParserCache(mIsUpgrade);
2569
2570            // Set flag to monitor and not change apk file paths when
2571            // scanning install directories.
2572            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2573
2574            if (mIsUpgrade || mFirstBoot) {
2575                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2576            }
2577
2578            // Collect vendor overlay packages. (Do this before scanning any apps.)
2579            // For security and version matching reason, only consider
2580            // overlay packages if they reside in the right directory.
2581            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2582                    | PackageParser.PARSE_IS_SYSTEM
2583                    | PackageParser.PARSE_IS_SYSTEM_DIR
2584                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2585
2586            mParallelPackageParserCallback.findStaticOverlayPackages();
2587
2588            // Find base frameworks (resource packages without code).
2589            scanDirTracedLI(frameworkDir, mDefParseFlags
2590                    | PackageParser.PARSE_IS_SYSTEM
2591                    | PackageParser.PARSE_IS_SYSTEM_DIR
2592                    | PackageParser.PARSE_IS_PRIVILEGED,
2593                    scanFlags | SCAN_NO_DEX, 0);
2594
2595            // Collected privileged system packages.
2596            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2597            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2598                    | PackageParser.PARSE_IS_SYSTEM
2599                    | PackageParser.PARSE_IS_SYSTEM_DIR
2600                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2601
2602            // Collect ordinary system packages.
2603            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2604            scanDirTracedLI(systemAppDir, mDefParseFlags
2605                    | PackageParser.PARSE_IS_SYSTEM
2606                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2607
2608            // Collect all vendor packages.
2609            File vendorAppDir = new File("/vendor/app");
2610            try {
2611                vendorAppDir = vendorAppDir.getCanonicalFile();
2612            } catch (IOException e) {
2613                // failed to look up canonical path, continue with original one
2614            }
2615            scanDirTracedLI(vendorAppDir, mDefParseFlags
2616                    | PackageParser.PARSE_IS_SYSTEM
2617                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2618
2619            // Collect all OEM packages.
2620            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2621            scanDirTracedLI(oemAppDir, mDefParseFlags
2622                    | PackageParser.PARSE_IS_SYSTEM
2623                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2624
2625            // Prune any system packages that no longer exist.
2626            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2627            if (!mOnlyCore) {
2628                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2629                while (psit.hasNext()) {
2630                    PackageSetting ps = psit.next();
2631
2632                    /*
2633                     * If this is not a system app, it can't be a
2634                     * disable system app.
2635                     */
2636                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2637                        continue;
2638                    }
2639
2640                    /*
2641                     * If the package is scanned, it's not erased.
2642                     */
2643                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2644                    if (scannedPkg != null) {
2645                        /*
2646                         * If the system app is both scanned and in the
2647                         * disabled packages list, then it must have been
2648                         * added via OTA. Remove it from the currently
2649                         * scanned package so the previously user-installed
2650                         * application can be scanned.
2651                         */
2652                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2653                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2654                                    + ps.name + "; removing system app.  Last known codePath="
2655                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2656                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2657                                    + scannedPkg.mVersionCode);
2658                            removePackageLI(scannedPkg, true);
2659                            mExpectingBetter.put(ps.name, ps.codePath);
2660                        }
2661
2662                        continue;
2663                    }
2664
2665                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2666                        psit.remove();
2667                        logCriticalInfo(Log.WARN, "System package " + ps.name
2668                                + " no longer exists; it's data will be wiped");
2669                        // Actual deletion of code and data will be handled by later
2670                        // reconciliation step
2671                    } else {
2672                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2673                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2674                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2675                        }
2676                    }
2677                }
2678            }
2679
2680            //look for any incomplete package installations
2681            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2682            for (int i = 0; i < deletePkgsList.size(); i++) {
2683                // Actual deletion of code and data will be handled by later
2684                // reconciliation step
2685                final String packageName = deletePkgsList.get(i).name;
2686                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2687                synchronized (mPackages) {
2688                    mSettings.removePackageLPw(packageName);
2689                }
2690            }
2691
2692            //delete tmp files
2693            deleteTempPackageFiles();
2694
2695            // Remove any shared userIDs that have no associated packages
2696            mSettings.pruneSharedUsersLPw();
2697
2698            if (!mOnlyCore) {
2699                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2700                        SystemClock.uptimeMillis());
2701                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2702
2703                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2704                        | PackageParser.PARSE_FORWARD_LOCK,
2705                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2706
2707                /**
2708                 * Remove disable package settings for any updated system
2709                 * apps that were removed via an OTA. If they're not a
2710                 * previously-updated app, remove them completely.
2711                 * Otherwise, just revoke their system-level permissions.
2712                 */
2713                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2714                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2715                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2716
2717                    String msg;
2718                    if (deletedPkg == null) {
2719                        msg = "Updated system package " + deletedAppName
2720                                + " no longer exists; it's data will be wiped";
2721                        // Actual deletion of code and data will be handled by later
2722                        // reconciliation step
2723                    } else {
2724                        msg = "Updated system app + " + deletedAppName
2725                                + " no longer present; removing system privileges for "
2726                                + deletedAppName;
2727
2728                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2729
2730                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2731                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2732                    }
2733                    logCriticalInfo(Log.WARN, msg);
2734                }
2735
2736                /**
2737                 * Make sure all system apps that we expected to appear on
2738                 * the userdata partition actually showed up. If they never
2739                 * appeared, crawl back and revive the system version.
2740                 */
2741                for (int i = 0; i < mExpectingBetter.size(); i++) {
2742                    final String packageName = mExpectingBetter.keyAt(i);
2743                    if (!mPackages.containsKey(packageName)) {
2744                        final File scanFile = mExpectingBetter.valueAt(i);
2745
2746                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2747                                + " but never showed up; reverting to system");
2748
2749                        int reparseFlags = mDefParseFlags;
2750                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2751                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2752                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2753                                    | PackageParser.PARSE_IS_PRIVILEGED;
2754                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2755                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2756                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2757                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2758                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2759                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2760                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2761                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2762                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2763                        } else {
2764                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2765                            continue;
2766                        }
2767
2768                        mSettings.enableSystemPackageLPw(packageName);
2769
2770                        try {
2771                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2772                        } catch (PackageManagerException e) {
2773                            Slog.e(TAG, "Failed to parse original system package: "
2774                                    + e.getMessage());
2775                        }
2776                    }
2777                }
2778            }
2779            mExpectingBetter.clear();
2780
2781            // Resolve the storage manager.
2782            mStorageManagerPackage = getStorageManagerPackageName();
2783
2784            // Resolve protected action filters. Only the setup wizard is allowed to
2785            // have a high priority filter for these actions.
2786            mSetupWizardPackage = getSetupWizardPackageName();
2787            if (mProtectedFilters.size() > 0) {
2788                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2789                    Slog.i(TAG, "No setup wizard;"
2790                        + " All protected intents capped to priority 0");
2791                }
2792                for (ActivityIntentInfo filter : mProtectedFilters) {
2793                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2794                        if (DEBUG_FILTERS) {
2795                            Slog.i(TAG, "Found setup wizard;"
2796                                + " allow priority " + filter.getPriority() + ";"
2797                                + " package: " + filter.activity.info.packageName
2798                                + " activity: " + filter.activity.className
2799                                + " priority: " + filter.getPriority());
2800                        }
2801                        // skip setup wizard; allow it to keep the high priority filter
2802                        continue;
2803                    }
2804                    if (DEBUG_FILTERS) {
2805                        Slog.i(TAG, "Protected action; cap priority to 0;"
2806                                + " package: " + filter.activity.info.packageName
2807                                + " activity: " + filter.activity.className
2808                                + " origPrio: " + filter.getPriority());
2809                    }
2810                    filter.setPriority(0);
2811                }
2812            }
2813            mDeferProtectedFilters = false;
2814            mProtectedFilters.clear();
2815
2816            // Now that we know all of the shared libraries, update all clients to have
2817            // the correct library paths.
2818            updateAllSharedLibrariesLPw(null);
2819
2820            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2821                // NOTE: We ignore potential failures here during a system scan (like
2822                // the rest of the commands above) because there's precious little we
2823                // can do about it. A settings error is reported, though.
2824                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2825            }
2826
2827            // Now that we know all the packages we are keeping,
2828            // read and update their last usage times.
2829            mPackageUsage.read(mPackages);
2830            mCompilerStats.read();
2831
2832            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2833                    SystemClock.uptimeMillis());
2834            Slog.i(TAG, "Time to scan packages: "
2835                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2836                    + " seconds");
2837
2838            // If the platform SDK has changed since the last time we booted,
2839            // we need to re-grant app permission to catch any new ones that
2840            // appear.  This is really a hack, and means that apps can in some
2841            // cases get permissions that the user didn't initially explicitly
2842            // allow...  it would be nice to have some better way to handle
2843            // this situation.
2844            int updateFlags = UPDATE_PERMISSIONS_ALL;
2845            if (ver.sdkVersion != mSdkVersion) {
2846                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2847                        + mSdkVersion + "; regranting permissions for internal storage");
2848                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2849            }
2850            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2851            ver.sdkVersion = mSdkVersion;
2852
2853            // If this is the first boot or an update from pre-M, and it is a normal
2854            // boot, then we need to initialize the default preferred apps across
2855            // all defined users.
2856            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2857                for (UserInfo user : sUserManager.getUsers(true)) {
2858                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2859                    applyFactoryDefaultBrowserLPw(user.id);
2860                    primeDomainVerificationsLPw(user.id);
2861                }
2862            }
2863
2864            // Prepare storage for system user really early during boot,
2865            // since core system apps like SettingsProvider and SystemUI
2866            // can't wait for user to start
2867            final int storageFlags;
2868            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2869                storageFlags = StorageManager.FLAG_STORAGE_DE;
2870            } else {
2871                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2872            }
2873            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2874                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2875                    true /* onlyCoreApps */);
2876            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2877                BootTimingsTraceLog traceLog = new BootTimingsTraceLog("SystemServerTimingAsync",
2878                        Trace.TRACE_TAG_PACKAGE_MANAGER);
2879                traceLog.traceBegin("AppDataFixup");
2880                try {
2881                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
2882                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2883                } catch (InstallerException e) {
2884                    Slog.w(TAG, "Trouble fixing GIDs", e);
2885                }
2886                traceLog.traceEnd();
2887
2888                traceLog.traceBegin("AppDataPrepare");
2889                if (deferPackages == null || deferPackages.isEmpty()) {
2890                    return;
2891                }
2892                int count = 0;
2893                for (String pkgName : deferPackages) {
2894                    PackageParser.Package pkg = null;
2895                    synchronized (mPackages) {
2896                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
2897                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
2898                            pkg = ps.pkg;
2899                        }
2900                    }
2901                    if (pkg != null) {
2902                        synchronized (mInstallLock) {
2903                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
2904                                    true /* maybeMigrateAppData */);
2905                        }
2906                        count++;
2907                    }
2908                }
2909                traceLog.traceEnd();
2910                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
2911            }, "prepareAppData");
2912
2913            // If this is first boot after an OTA, and a normal boot, then
2914            // we need to clear code cache directories.
2915            // Note that we do *not* clear the application profiles. These remain valid
2916            // across OTAs and are used to drive profile verification (post OTA) and
2917            // profile compilation (without waiting to collect a fresh set of profiles).
2918            if (mIsUpgrade && !onlyCore) {
2919                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2920                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2921                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2922                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2923                        // No apps are running this early, so no need to freeze
2924                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2925                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2926                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2927                    }
2928                }
2929                ver.fingerprint = Build.FINGERPRINT;
2930            }
2931
2932            checkDefaultBrowser();
2933
2934            // clear only after permissions and other defaults have been updated
2935            mExistingSystemPackages.clear();
2936            mPromoteSystemApps = false;
2937
2938            // All the changes are done during package scanning.
2939            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2940
2941            // can downgrade to reader
2942            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
2943            mSettings.writeLPr();
2944            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2945            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2946                    SystemClock.uptimeMillis());
2947
2948            if (!mOnlyCore) {
2949                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2950                mRequiredInstallerPackage = getRequiredInstallerLPr();
2951                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2952                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2953                if (mIntentFilterVerifierComponent != null) {
2954                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2955                            mIntentFilterVerifierComponent);
2956                } else {
2957                    mIntentFilterVerifier = null;
2958                }
2959                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2960                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
2961                        SharedLibraryInfo.VERSION_UNDEFINED);
2962                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2963                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
2964                        SharedLibraryInfo.VERSION_UNDEFINED);
2965            } else {
2966                mRequiredVerifierPackage = null;
2967                mRequiredInstallerPackage = null;
2968                mRequiredUninstallerPackage = null;
2969                mIntentFilterVerifierComponent = null;
2970                mIntentFilterVerifier = null;
2971                mServicesSystemSharedLibraryPackageName = null;
2972                mSharedSystemSharedLibraryPackageName = null;
2973            }
2974
2975            mInstallerService = new PackageInstallerService(context, this);
2976            final Pair<ComponentName, String> instantAppResolverComponent =
2977                    getInstantAppResolverLPr();
2978            if (instantAppResolverComponent != null) {
2979                if (DEBUG_EPHEMERAL) {
2980                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
2981                }
2982                mInstantAppResolverConnection = new EphemeralResolverConnection(
2983                        mContext, instantAppResolverComponent.first,
2984                        instantAppResolverComponent.second);
2985                mInstantAppResolverSettingsComponent =
2986                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
2987            } else {
2988                mInstantAppResolverConnection = null;
2989                mInstantAppResolverSettingsComponent = null;
2990            }
2991            updateInstantAppInstallerLocked(null);
2992
2993            // Read and update the usage of dex files.
2994            // Do this at the end of PM init so that all the packages have their
2995            // data directory reconciled.
2996            // At this point we know the code paths of the packages, so we can validate
2997            // the disk file and build the internal cache.
2998            // The usage file is expected to be small so loading and verifying it
2999            // should take a fairly small time compare to the other activities (e.g. package
3000            // scanning).
3001            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3002            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3003            for (int userId : currentUserIds) {
3004                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3005            }
3006            mDexManager.load(userPackages);
3007        } // synchronized (mPackages)
3008        } // synchronized (mInstallLock)
3009
3010        // Now after opening every single application zip, make sure they
3011        // are all flushed.  Not really needed, but keeps things nice and
3012        // tidy.
3013        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3014        Runtime.getRuntime().gc();
3015        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3016
3017        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3018        FallbackCategoryProvider.loadFallbacks();
3019        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3020
3021        // The initial scanning above does many calls into installd while
3022        // holding the mPackages lock, but we're mostly interested in yelling
3023        // once we have a booted system.
3024        mInstaller.setWarnIfHeld(mPackages);
3025
3026        // Expose private service for system components to use.
3027        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
3028        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3029    }
3030
3031    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3032        // we're only interested in updating the installer appliction when 1) it's not
3033        // already set or 2) the modified package is the installer
3034        if (mInstantAppInstallerActivity != null
3035                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3036                        .equals(modifiedPackage)) {
3037            return;
3038        }
3039        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3040    }
3041
3042    private static File preparePackageParserCache(boolean isUpgrade) {
3043        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3044            return null;
3045        }
3046
3047        // Disable package parsing on eng builds to allow for faster incremental development.
3048        if ("eng".equals(Build.TYPE)) {
3049            return null;
3050        }
3051
3052        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3053            Slog.i(TAG, "Disabling package parser cache due to system property.");
3054            return null;
3055        }
3056
3057        // The base directory for the package parser cache lives under /data/system/.
3058        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3059                "package_cache");
3060        if (cacheBaseDir == null) {
3061            return null;
3062        }
3063
3064        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3065        // This also serves to "GC" unused entries when the package cache version changes (which
3066        // can only happen during upgrades).
3067        if (isUpgrade) {
3068            FileUtils.deleteContents(cacheBaseDir);
3069        }
3070
3071
3072        // Return the versioned package cache directory. This is something like
3073        // "/data/system/package_cache/1"
3074        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3075
3076        // The following is a workaround to aid development on non-numbered userdebug
3077        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3078        // the system partition is newer.
3079        //
3080        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3081        // that starts with "eng." to signify that this is an engineering build and not
3082        // destined for release.
3083        if ("userdebug".equals(Build.TYPE) && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3084            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3085
3086            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3087            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3088            // in general and should not be used for production changes. In this specific case,
3089            // we know that they will work.
3090            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3091            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3092                FileUtils.deleteContents(cacheBaseDir);
3093                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3094            }
3095        }
3096
3097        return cacheDir;
3098    }
3099
3100    @Override
3101    public boolean isFirstBoot() {
3102        // allow instant applications
3103        return mFirstBoot;
3104    }
3105
3106    @Override
3107    public boolean isOnlyCoreApps() {
3108        // allow instant applications
3109        return mOnlyCore;
3110    }
3111
3112    @Override
3113    public boolean isUpgrade() {
3114        // allow instant applications
3115        return mIsUpgrade;
3116    }
3117
3118    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3119        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3120
3121        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3122                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3123                UserHandle.USER_SYSTEM);
3124        if (matches.size() == 1) {
3125            return matches.get(0).getComponentInfo().packageName;
3126        } else if (matches.size() == 0) {
3127            Log.e(TAG, "There should probably be a verifier, but, none were found");
3128            return null;
3129        }
3130        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3131    }
3132
3133    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3134        synchronized (mPackages) {
3135            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3136            if (libraryEntry == null) {
3137                throw new IllegalStateException("Missing required shared library:" + name);
3138            }
3139            return libraryEntry.apk;
3140        }
3141    }
3142
3143    private @NonNull String getRequiredInstallerLPr() {
3144        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3145        intent.addCategory(Intent.CATEGORY_DEFAULT);
3146        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3147
3148        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3149                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3150                UserHandle.USER_SYSTEM);
3151        if (matches.size() == 1) {
3152            ResolveInfo resolveInfo = matches.get(0);
3153            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3154                throw new RuntimeException("The installer must be a privileged app");
3155            }
3156            return matches.get(0).getComponentInfo().packageName;
3157        } else {
3158            throw new RuntimeException("There must be exactly one installer; found " + matches);
3159        }
3160    }
3161
3162    private @NonNull String getRequiredUninstallerLPr() {
3163        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3164        intent.addCategory(Intent.CATEGORY_DEFAULT);
3165        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3166
3167        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3168                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3169                UserHandle.USER_SYSTEM);
3170        if (resolveInfo == null ||
3171                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3172            throw new RuntimeException("There must be exactly one uninstaller; found "
3173                    + resolveInfo);
3174        }
3175        return resolveInfo.getComponentInfo().packageName;
3176    }
3177
3178    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3179        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3180
3181        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3182                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3183                UserHandle.USER_SYSTEM);
3184        ResolveInfo best = null;
3185        final int N = matches.size();
3186        for (int i = 0; i < N; i++) {
3187            final ResolveInfo cur = matches.get(i);
3188            final String packageName = cur.getComponentInfo().packageName;
3189            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3190                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3191                continue;
3192            }
3193
3194            if (best == null || cur.priority > best.priority) {
3195                best = cur;
3196            }
3197        }
3198
3199        if (best != null) {
3200            return best.getComponentInfo().getComponentName();
3201        }
3202        Slog.w(TAG, "Intent filter verifier not found");
3203        return null;
3204    }
3205
3206    @Override
3207    public @Nullable ComponentName getInstantAppResolverComponent() {
3208        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3209            return null;
3210        }
3211        synchronized (mPackages) {
3212            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3213            if (instantAppResolver == null) {
3214                return null;
3215            }
3216            return instantAppResolver.first;
3217        }
3218    }
3219
3220    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3221        final String[] packageArray =
3222                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3223        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3224            if (DEBUG_EPHEMERAL) {
3225                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3226            }
3227            return null;
3228        }
3229
3230        final int callingUid = Binder.getCallingUid();
3231        final int resolveFlags =
3232                MATCH_DIRECT_BOOT_AWARE
3233                | MATCH_DIRECT_BOOT_UNAWARE
3234                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3235        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3236        final Intent resolverIntent = new Intent(actionName);
3237        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3238                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3239        // temporarily look for the old action
3240        if (resolvers.size() == 0) {
3241            if (DEBUG_EPHEMERAL) {
3242                Slog.d(TAG, "Ephemeral resolver not found with new action; try old one");
3243            }
3244            actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE;
3245            resolverIntent.setAction(actionName);
3246            resolvers = queryIntentServicesInternal(resolverIntent, null,
3247                    resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3248        }
3249        final int N = resolvers.size();
3250        if (N == 0) {
3251            if (DEBUG_EPHEMERAL) {
3252                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3253            }
3254            return null;
3255        }
3256
3257        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3258        for (int i = 0; i < N; i++) {
3259            final ResolveInfo info = resolvers.get(i);
3260
3261            if (info.serviceInfo == null) {
3262                continue;
3263            }
3264
3265            final String packageName = info.serviceInfo.packageName;
3266            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3267                if (DEBUG_EPHEMERAL) {
3268                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3269                            + " pkg: " + packageName + ", info:" + info);
3270                }
3271                continue;
3272            }
3273
3274            if (DEBUG_EPHEMERAL) {
3275                Slog.v(TAG, "Ephemeral resolver found;"
3276                        + " pkg: " + packageName + ", info:" + info);
3277            }
3278            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3279        }
3280        if (DEBUG_EPHEMERAL) {
3281            Slog.v(TAG, "Ephemeral resolver NOT found");
3282        }
3283        return null;
3284    }
3285
3286    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3287        final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE);
3288        intent.addCategory(Intent.CATEGORY_DEFAULT);
3289        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3290
3291        final int resolveFlags =
3292                MATCH_DIRECT_BOOT_AWARE
3293                | MATCH_DIRECT_BOOT_UNAWARE
3294                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3295        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3296                resolveFlags, UserHandle.USER_SYSTEM);
3297        // temporarily look for the old action
3298        if (matches.isEmpty()) {
3299            if (DEBUG_EPHEMERAL) {
3300                Slog.d(TAG, "Ephemeral installer not found with new action; try old one");
3301            }
3302            intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3303            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3304                    resolveFlags, UserHandle.USER_SYSTEM);
3305        }
3306        Iterator<ResolveInfo> iter = matches.iterator();
3307        while (iter.hasNext()) {
3308            final ResolveInfo rInfo = iter.next();
3309            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3310            if (ps != null) {
3311                final PermissionsState permissionsState = ps.getPermissionsState();
3312                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3313                    continue;
3314                }
3315            }
3316            iter.remove();
3317        }
3318        if (matches.size() == 0) {
3319            return null;
3320        } else if (matches.size() == 1) {
3321            return (ActivityInfo) matches.get(0).getComponentInfo();
3322        } else {
3323            throw new RuntimeException(
3324                    "There must be at most one ephemeral installer; found " + matches);
3325        }
3326    }
3327
3328    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3329            @NonNull ComponentName resolver) {
3330        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3331                .addCategory(Intent.CATEGORY_DEFAULT)
3332                .setPackage(resolver.getPackageName());
3333        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3334        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3335                UserHandle.USER_SYSTEM);
3336        // temporarily look for the old action
3337        if (matches.isEmpty()) {
3338            if (DEBUG_EPHEMERAL) {
3339                Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one");
3340            }
3341            intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS);
3342            matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3343                    UserHandle.USER_SYSTEM);
3344        }
3345        if (matches.isEmpty()) {
3346            return null;
3347        }
3348        return matches.get(0).getComponentInfo().getComponentName();
3349    }
3350
3351    private void primeDomainVerificationsLPw(int userId) {
3352        if (DEBUG_DOMAIN_VERIFICATION) {
3353            Slog.d(TAG, "Priming domain verifications in user " + userId);
3354        }
3355
3356        SystemConfig systemConfig = SystemConfig.getInstance();
3357        ArraySet<String> packages = systemConfig.getLinkedApps();
3358
3359        for (String packageName : packages) {
3360            PackageParser.Package pkg = mPackages.get(packageName);
3361            if (pkg != null) {
3362                if (!pkg.isSystemApp()) {
3363                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3364                    continue;
3365                }
3366
3367                ArraySet<String> domains = null;
3368                for (PackageParser.Activity a : pkg.activities) {
3369                    for (ActivityIntentInfo filter : a.intents) {
3370                        if (hasValidDomains(filter)) {
3371                            if (domains == null) {
3372                                domains = new ArraySet<String>();
3373                            }
3374                            domains.addAll(filter.getHostsList());
3375                        }
3376                    }
3377                }
3378
3379                if (domains != null && domains.size() > 0) {
3380                    if (DEBUG_DOMAIN_VERIFICATION) {
3381                        Slog.v(TAG, "      + " + packageName);
3382                    }
3383                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3384                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3385                    // and then 'always' in the per-user state actually used for intent resolution.
3386                    final IntentFilterVerificationInfo ivi;
3387                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3388                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3389                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3390                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3391                } else {
3392                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3393                            + "' does not handle web links");
3394                }
3395            } else {
3396                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3397            }
3398        }
3399
3400        scheduleWritePackageRestrictionsLocked(userId);
3401        scheduleWriteSettingsLocked();
3402    }
3403
3404    private void applyFactoryDefaultBrowserLPw(int userId) {
3405        // The default browser app's package name is stored in a string resource,
3406        // with a product-specific overlay used for vendor customization.
3407        String browserPkg = mContext.getResources().getString(
3408                com.android.internal.R.string.default_browser);
3409        if (!TextUtils.isEmpty(browserPkg)) {
3410            // non-empty string => required to be a known package
3411            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3412            if (ps == null) {
3413                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3414                browserPkg = null;
3415            } else {
3416                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3417            }
3418        }
3419
3420        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3421        // default.  If there's more than one, just leave everything alone.
3422        if (browserPkg == null) {
3423            calculateDefaultBrowserLPw(userId);
3424        }
3425    }
3426
3427    private void calculateDefaultBrowserLPw(int userId) {
3428        List<String> allBrowsers = resolveAllBrowserApps(userId);
3429        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3430        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3431    }
3432
3433    private List<String> resolveAllBrowserApps(int userId) {
3434        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3435        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3436                PackageManager.MATCH_ALL, userId);
3437
3438        final int count = list.size();
3439        List<String> result = new ArrayList<String>(count);
3440        for (int i=0; i<count; i++) {
3441            ResolveInfo info = list.get(i);
3442            if (info.activityInfo == null
3443                    || !info.handleAllWebDataURI
3444                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3445                    || result.contains(info.activityInfo.packageName)) {
3446                continue;
3447            }
3448            result.add(info.activityInfo.packageName);
3449        }
3450
3451        return result;
3452    }
3453
3454    private boolean packageIsBrowser(String packageName, int userId) {
3455        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3456                PackageManager.MATCH_ALL, userId);
3457        final int N = list.size();
3458        for (int i = 0; i < N; i++) {
3459            ResolveInfo info = list.get(i);
3460            if (packageName.equals(info.activityInfo.packageName)) {
3461                return true;
3462            }
3463        }
3464        return false;
3465    }
3466
3467    private void checkDefaultBrowser() {
3468        final int myUserId = UserHandle.myUserId();
3469        final String packageName = getDefaultBrowserPackageName(myUserId);
3470        if (packageName != null) {
3471            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3472            if (info == null) {
3473                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3474                synchronized (mPackages) {
3475                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3476                }
3477            }
3478        }
3479    }
3480
3481    @Override
3482    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3483            throws RemoteException {
3484        try {
3485            return super.onTransact(code, data, reply, flags);
3486        } catch (RuntimeException e) {
3487            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3488                Slog.wtf(TAG, "Package Manager Crash", e);
3489            }
3490            throw e;
3491        }
3492    }
3493
3494    static int[] appendInts(int[] cur, int[] add) {
3495        if (add == null) return cur;
3496        if (cur == null) return add;
3497        final int N = add.length;
3498        for (int i=0; i<N; i++) {
3499            cur = appendInt(cur, add[i]);
3500        }
3501        return cur;
3502    }
3503
3504    /**
3505     * Returns whether or not a full application can see an instant application.
3506     * <p>
3507     * Currently, there are three cases in which this can occur:
3508     * <ol>
3509     * <li>The calling application is a "special" process. The special
3510     *     processes are {@link Process#SYSTEM_UID}, {@link Process#SHELL_UID}
3511     *     and {@code 0}</li>
3512     * <li>The calling application has the permission
3513     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}</li>
3514     * <li>The calling application is the default launcher on the
3515     *     system partition.</li>
3516     * </ol>
3517     */
3518    private boolean canViewInstantApps(int callingUid, int userId) {
3519        if (callingUid == Process.SYSTEM_UID
3520                || callingUid == Process.SHELL_UID
3521                || callingUid == Process.ROOT_UID) {
3522            return true;
3523        }
3524        if (mContext.checkCallingOrSelfPermission(
3525                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3526            return true;
3527        }
3528        if (mContext.checkCallingOrSelfPermission(
3529                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3530            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3531            if (homeComponent != null
3532                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3533                return true;
3534            }
3535        }
3536        return false;
3537    }
3538
3539    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3540        if (!sUserManager.exists(userId)) return null;
3541        if (ps == null) {
3542            return null;
3543        }
3544        PackageParser.Package p = ps.pkg;
3545        if (p == null) {
3546            return null;
3547        }
3548        final int callingUid = Binder.getCallingUid();
3549        // Filter out ephemeral app metadata:
3550        //   * The system/shell/root can see metadata for any app
3551        //   * An installed app can see metadata for 1) other installed apps
3552        //     and 2) ephemeral apps that have explicitly interacted with it
3553        //   * Ephemeral apps can only see their own data and exposed installed apps
3554        //   * Holding a signature permission allows seeing instant apps
3555        if (filterAppAccessLPr(ps, callingUid, userId)) {
3556            return null;
3557        }
3558
3559        final PermissionsState permissionsState = ps.getPermissionsState();
3560
3561        // Compute GIDs only if requested
3562        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3563                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3564        // Compute granted permissions only if package has requested permissions
3565        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3566                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3567        final PackageUserState state = ps.readUserState(userId);
3568
3569        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3570                && ps.isSystem()) {
3571            flags |= MATCH_ANY_USER;
3572        }
3573
3574        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3575                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3576
3577        if (packageInfo == null) {
3578            return null;
3579        }
3580
3581        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3582                resolveExternalPackageNameLPr(p);
3583
3584        return packageInfo;
3585    }
3586
3587    @Override
3588    public void checkPackageStartable(String packageName, int userId) {
3589        final int callingUid = Binder.getCallingUid();
3590        if (getInstantAppPackageName(callingUid) != null) {
3591            throw new SecurityException("Instant applications don't have access to this method");
3592        }
3593        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3594        synchronized (mPackages) {
3595            final PackageSetting ps = mSettings.mPackages.get(packageName);
3596            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3597                throw new SecurityException("Package " + packageName + " was not found!");
3598            }
3599
3600            if (!ps.getInstalled(userId)) {
3601                throw new SecurityException(
3602                        "Package " + packageName + " was not installed for user " + userId + "!");
3603            }
3604
3605            if (mSafeMode && !ps.isSystem()) {
3606                throw new SecurityException("Package " + packageName + " not a system app!");
3607            }
3608
3609            if (mFrozenPackages.contains(packageName)) {
3610                throw new SecurityException("Package " + packageName + " is currently frozen!");
3611            }
3612
3613            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3614                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3615                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3616            }
3617        }
3618    }
3619
3620    @Override
3621    public boolean isPackageAvailable(String packageName, int userId) {
3622        if (!sUserManager.exists(userId)) return false;
3623        final int callingUid = Binder.getCallingUid();
3624        enforceCrossUserPermission(callingUid, userId,
3625                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
3626        synchronized (mPackages) {
3627            PackageParser.Package p = mPackages.get(packageName);
3628            if (p != null) {
3629                final PackageSetting ps = (PackageSetting) p.mExtras;
3630                if (filterAppAccessLPr(ps, callingUid, userId)) {
3631                    return false;
3632                }
3633                if (ps != null) {
3634                    final PackageUserState state = ps.readUserState(userId);
3635                    if (state != null) {
3636                        return PackageParser.isAvailable(state);
3637                    }
3638                }
3639            }
3640        }
3641        return false;
3642    }
3643
3644    @Override
3645    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3646        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3647                flags, Binder.getCallingUid(), userId);
3648    }
3649
3650    @Override
3651    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3652            int flags, int userId) {
3653        return getPackageInfoInternal(versionedPackage.getPackageName(),
3654                versionedPackage.getVersionCode(), flags, Binder.getCallingUid(), userId);
3655    }
3656
3657    /**
3658     * Important: The provided filterCallingUid is used exclusively to filter out packages
3659     * that can be seen based on user state. It's typically the original caller uid prior
3660     * to clearing. Because it can only be provided by trusted code, it's value can be
3661     * trusted and will be used as-is; unlike userId which will be validated by this method.
3662     */
3663    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3664            int flags, int filterCallingUid, int userId) {
3665        if (!sUserManager.exists(userId)) return null;
3666        flags = updateFlagsForPackage(flags, userId, packageName);
3667        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3668                false /* requireFullPermission */, false /* checkShell */, "get package info");
3669
3670        // reader
3671        synchronized (mPackages) {
3672            // Normalize package name to handle renamed packages and static libs
3673            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3674
3675            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3676            if (matchFactoryOnly) {
3677                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3678                if (ps != null) {
3679                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3680                        return null;
3681                    }
3682                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3683                        return null;
3684                    }
3685                    return generatePackageInfo(ps, flags, userId);
3686                }
3687            }
3688
3689            PackageParser.Package p = mPackages.get(packageName);
3690            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3691                return null;
3692            }
3693            if (DEBUG_PACKAGE_INFO)
3694                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3695            if (p != null) {
3696                final PackageSetting ps = (PackageSetting) p.mExtras;
3697                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3698                    return null;
3699                }
3700                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
3701                    return null;
3702                }
3703                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3704            }
3705            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3706                final PackageSetting ps = mSettings.mPackages.get(packageName);
3707                if (ps == null) return null;
3708                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3709                    return null;
3710                }
3711                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3712                    return null;
3713                }
3714                return generatePackageInfo(ps, flags, userId);
3715            }
3716        }
3717        return null;
3718    }
3719
3720    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
3721        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
3722            return true;
3723        }
3724        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
3725            return true;
3726        }
3727        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
3728            return true;
3729        }
3730        return false;
3731    }
3732
3733    private boolean isComponentVisibleToInstantApp(
3734            @Nullable ComponentName component, @ComponentType int type) {
3735        if (type == TYPE_ACTIVITY) {
3736            final PackageParser.Activity activity = mActivities.mActivities.get(component);
3737            return activity != null
3738                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3739                    : false;
3740        } else if (type == TYPE_RECEIVER) {
3741            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
3742            return activity != null
3743                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3744                    : false;
3745        } else if (type == TYPE_SERVICE) {
3746            final PackageParser.Service service = mServices.mServices.get(component);
3747            return service != null
3748                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3749                    : false;
3750        } else if (type == TYPE_PROVIDER) {
3751            final PackageParser.Provider provider = mProviders.mProviders.get(component);
3752            return provider != null
3753                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3754                    : false;
3755        } else if (type == TYPE_UNKNOWN) {
3756            return isComponentVisibleToInstantApp(component);
3757        }
3758        return false;
3759    }
3760
3761    /**
3762     * Returns whether or not access to the application should be filtered.
3763     * <p>
3764     * Access may be limited based upon whether the calling or target applications
3765     * are instant applications.
3766     *
3767     * @see #canAccessInstantApps(int)
3768     */
3769    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
3770            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
3771        // if we're in an isolated process, get the real calling UID
3772        if (Process.isIsolated(callingUid)) {
3773            callingUid = mIsolatedOwners.get(callingUid);
3774        }
3775        final String instantAppPkgName = getInstantAppPackageName(callingUid);
3776        final boolean callerIsInstantApp = instantAppPkgName != null;
3777        if (ps == null) {
3778            if (callerIsInstantApp) {
3779                // pretend the application exists, but, needs to be filtered
3780                return true;
3781            }
3782            return false;
3783        }
3784        // if the target and caller are the same application, don't filter
3785        if (isCallerSameApp(ps.name, callingUid)) {
3786            return false;
3787        }
3788        if (callerIsInstantApp) {
3789            // request for a specific component; if it hasn't been explicitly exposed, filter
3790            if (component != null) {
3791                return !isComponentVisibleToInstantApp(component, componentType);
3792            }
3793            // request for application; if no components have been explicitly exposed, filter
3794            return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps;
3795        }
3796        if (ps.getInstantApp(userId)) {
3797            // caller can see all components of all instant applications, don't filter
3798            if (canViewInstantApps(callingUid, userId)) {
3799                return false;
3800            }
3801            // request for a specific instant application component, filter
3802            if (component != null) {
3803                return true;
3804            }
3805            // request for an instant application; if the caller hasn't been granted access, filter
3806            return !mInstantAppRegistry.isInstantAccessGranted(
3807                    userId, UserHandle.getAppId(callingUid), ps.appId);
3808        }
3809        return false;
3810    }
3811
3812    /**
3813     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
3814     */
3815    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
3816        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
3817    }
3818
3819    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
3820            int flags) {
3821        // Callers can access only the libs they depend on, otherwise they need to explicitly
3822        // ask for the shared libraries given the caller is allowed to access all static libs.
3823        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
3824            // System/shell/root get to see all static libs
3825            final int appId = UserHandle.getAppId(uid);
3826            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
3827                    || appId == Process.ROOT_UID) {
3828                return false;
3829            }
3830        }
3831
3832        // No package means no static lib as it is always on internal storage
3833        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
3834            return false;
3835        }
3836
3837        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
3838                ps.pkg.staticSharedLibVersion);
3839        if (libEntry == null) {
3840            return false;
3841        }
3842
3843        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
3844        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
3845        if (uidPackageNames == null) {
3846            return true;
3847        }
3848
3849        for (String uidPackageName : uidPackageNames) {
3850            if (ps.name.equals(uidPackageName)) {
3851                return false;
3852            }
3853            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
3854            if (uidPs != null) {
3855                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
3856                        libEntry.info.getName());
3857                if (index < 0) {
3858                    continue;
3859                }
3860                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
3861                    return false;
3862                }
3863            }
3864        }
3865        return true;
3866    }
3867
3868    @Override
3869    public String[] currentToCanonicalPackageNames(String[] names) {
3870        final int callingUid = Binder.getCallingUid();
3871        if (getInstantAppPackageName(callingUid) != null) {
3872            return names;
3873        }
3874        final String[] out = new String[names.length];
3875        // reader
3876        synchronized (mPackages) {
3877            final int callingUserId = UserHandle.getUserId(callingUid);
3878            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
3879            for (int i=names.length-1; i>=0; i--) {
3880                final PackageSetting ps = mSettings.mPackages.get(names[i]);
3881                boolean translateName = false;
3882                if (ps != null && ps.realName != null) {
3883                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
3884                    translateName = !targetIsInstantApp
3885                            || canViewInstantApps
3886                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
3887                                    UserHandle.getAppId(callingUid), ps.appId);
3888                }
3889                out[i] = translateName ? ps.realName : names[i];
3890            }
3891        }
3892        return out;
3893    }
3894
3895    @Override
3896    public String[] canonicalToCurrentPackageNames(String[] names) {
3897        final int callingUid = Binder.getCallingUid();
3898        if (getInstantAppPackageName(callingUid) != null) {
3899            return names;
3900        }
3901        final String[] out = new String[names.length];
3902        // reader
3903        synchronized (mPackages) {
3904            final int callingUserId = UserHandle.getUserId(callingUid);
3905            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
3906            for (int i=names.length-1; i>=0; i--) {
3907                final String cur = mSettings.getRenamedPackageLPr(names[i]);
3908                boolean translateName = false;
3909                if (cur != null) {
3910                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
3911                    final boolean targetIsInstantApp =
3912                            ps != null && ps.getInstantApp(callingUserId);
3913                    translateName = !targetIsInstantApp
3914                            || canViewInstantApps
3915                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
3916                                    UserHandle.getAppId(callingUid), ps.appId);
3917                }
3918                out[i] = translateName ? cur : names[i];
3919            }
3920        }
3921        return out;
3922    }
3923
3924    @Override
3925    public int getPackageUid(String packageName, int flags, int userId) {
3926        if (!sUserManager.exists(userId)) return -1;
3927        final int callingUid = Binder.getCallingUid();
3928        flags = updateFlagsForPackage(flags, userId, packageName);
3929        enforceCrossUserPermission(callingUid, userId,
3930                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
3931
3932        // reader
3933        synchronized (mPackages) {
3934            final PackageParser.Package p = mPackages.get(packageName);
3935            if (p != null && p.isMatch(flags)) {
3936                PackageSetting ps = (PackageSetting) p.mExtras;
3937                if (filterAppAccessLPr(ps, callingUid, userId)) {
3938                    return -1;
3939                }
3940                return UserHandle.getUid(userId, p.applicationInfo.uid);
3941            }
3942            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3943                final PackageSetting ps = mSettings.mPackages.get(packageName);
3944                if (ps != null && ps.isMatch(flags)
3945                        && !filterAppAccessLPr(ps, callingUid, userId)) {
3946                    return UserHandle.getUid(userId, ps.appId);
3947                }
3948            }
3949        }
3950
3951        return -1;
3952    }
3953
3954    @Override
3955    public int[] getPackageGids(String packageName, int flags, int userId) {
3956        if (!sUserManager.exists(userId)) return null;
3957        final int callingUid = Binder.getCallingUid();
3958        flags = updateFlagsForPackage(flags, userId, packageName);
3959        enforceCrossUserPermission(callingUid, userId,
3960                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
3961
3962        // reader
3963        synchronized (mPackages) {
3964            final PackageParser.Package p = mPackages.get(packageName);
3965            if (p != null && p.isMatch(flags)) {
3966                PackageSetting ps = (PackageSetting) p.mExtras;
3967                if (filterAppAccessLPr(ps, callingUid, userId)) {
3968                    return null;
3969                }
3970                // TODO: Shouldn't this be checking for package installed state for userId and
3971                // return null?
3972                return ps.getPermissionsState().computeGids(userId);
3973            }
3974            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3975                final PackageSetting ps = mSettings.mPackages.get(packageName);
3976                if (ps != null && ps.isMatch(flags)
3977                        && !filterAppAccessLPr(ps, callingUid, userId)) {
3978                    return ps.getPermissionsState().computeGids(userId);
3979                }
3980            }
3981        }
3982
3983        return null;
3984    }
3985
3986    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3987        if (bp.perm != null) {
3988            return PackageParser.generatePermissionInfo(bp.perm, flags);
3989        }
3990        PermissionInfo pi = new PermissionInfo();
3991        pi.name = bp.name;
3992        pi.packageName = bp.sourcePackage;
3993        pi.nonLocalizedLabel = bp.name;
3994        pi.protectionLevel = bp.protectionLevel;
3995        return pi;
3996    }
3997
3998    @Override
3999    public PermissionInfo getPermissionInfo(String name, int flags) {
4000        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4001            return null;
4002        }
4003        // reader
4004        synchronized (mPackages) {
4005            final BasePermission p = mSettings.mPermissions.get(name);
4006            if (p != null) {
4007                return generatePermissionInfo(p, flags);
4008            }
4009            return null;
4010        }
4011    }
4012
4013    @Override
4014    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
4015            int flags) {
4016        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4017            return null;
4018        }
4019        // reader
4020        synchronized (mPackages) {
4021            if (group != null && !mPermissionGroups.containsKey(group)) {
4022                // This is thrown as NameNotFoundException
4023                return null;
4024            }
4025
4026            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
4027            for (BasePermission p : mSettings.mPermissions.values()) {
4028                if (group == null) {
4029                    if (p.perm == null || p.perm.info.group == null) {
4030                        out.add(generatePermissionInfo(p, flags));
4031                    }
4032                } else {
4033                    if (p.perm != null && group.equals(p.perm.info.group)) {
4034                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
4035                    }
4036                }
4037            }
4038            return new ParceledListSlice<>(out);
4039        }
4040    }
4041
4042    @Override
4043    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
4044        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4045            return null;
4046        }
4047        // reader
4048        synchronized (mPackages) {
4049            return PackageParser.generatePermissionGroupInfo(
4050                    mPermissionGroups.get(name), flags);
4051        }
4052    }
4053
4054    @Override
4055    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4056        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4057            return ParceledListSlice.emptyList();
4058        }
4059        // reader
4060        synchronized (mPackages) {
4061            final int N = mPermissionGroups.size();
4062            ArrayList<PermissionGroupInfo> out
4063                    = new ArrayList<PermissionGroupInfo>(N);
4064            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
4065                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
4066            }
4067            return new ParceledListSlice<>(out);
4068        }
4069    }
4070
4071    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4072            int filterCallingUid, int userId) {
4073        if (!sUserManager.exists(userId)) return null;
4074        PackageSetting ps = mSettings.mPackages.get(packageName);
4075        if (ps != null) {
4076            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4077                return null;
4078            }
4079            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4080                return null;
4081            }
4082            if (ps.pkg == null) {
4083                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4084                if (pInfo != null) {
4085                    return pInfo.applicationInfo;
4086                }
4087                return null;
4088            }
4089            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4090                    ps.readUserState(userId), userId);
4091            if (ai != null) {
4092                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4093            }
4094            return ai;
4095        }
4096        return null;
4097    }
4098
4099    @Override
4100    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4101        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4102    }
4103
4104    /**
4105     * Important: The provided filterCallingUid is used exclusively to filter out applications
4106     * that can be seen based on user state. It's typically the original caller uid prior
4107     * to clearing. Because it can only be provided by trusted code, it's value can be
4108     * trusted and will be used as-is; unlike userId which will be validated by this method.
4109     */
4110    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4111            int filterCallingUid, int userId) {
4112        if (!sUserManager.exists(userId)) return null;
4113        flags = updateFlagsForApplication(flags, userId, packageName);
4114        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4115                false /* requireFullPermission */, false /* checkShell */, "get application info");
4116
4117        // writer
4118        synchronized (mPackages) {
4119            // Normalize package name to handle renamed packages and static libs
4120            packageName = resolveInternalPackageNameLPr(packageName,
4121                    PackageManager.VERSION_CODE_HIGHEST);
4122
4123            PackageParser.Package p = mPackages.get(packageName);
4124            if (DEBUG_PACKAGE_INFO) Log.v(
4125                    TAG, "getApplicationInfo " + packageName
4126                    + ": " + p);
4127            if (p != null) {
4128                PackageSetting ps = mSettings.mPackages.get(packageName);
4129                if (ps == null) return null;
4130                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4131                    return null;
4132                }
4133                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4134                    return null;
4135                }
4136                // Note: isEnabledLP() does not apply here - always return info
4137                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4138                        p, flags, ps.readUserState(userId), userId);
4139                if (ai != null) {
4140                    ai.packageName = resolveExternalPackageNameLPr(p);
4141                }
4142                return ai;
4143            }
4144            if ("android".equals(packageName)||"system".equals(packageName)) {
4145                return mAndroidApplication;
4146            }
4147            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4148                // Already generates the external package name
4149                return generateApplicationInfoFromSettingsLPw(packageName,
4150                        flags, filterCallingUid, userId);
4151            }
4152        }
4153        return null;
4154    }
4155
4156    private String normalizePackageNameLPr(String packageName) {
4157        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4158        return normalizedPackageName != null ? normalizedPackageName : packageName;
4159    }
4160
4161    @Override
4162    public void deletePreloadsFileCache() {
4163        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4164            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4165        }
4166        File dir = Environment.getDataPreloadsFileCacheDirectory();
4167        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4168        FileUtils.deleteContents(dir);
4169    }
4170
4171    @Override
4172    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4173            final int storageFlags, final IPackageDataObserver observer) {
4174        mContext.enforceCallingOrSelfPermission(
4175                android.Manifest.permission.CLEAR_APP_CACHE, null);
4176        mHandler.post(() -> {
4177            boolean success = false;
4178            try {
4179                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4180                success = true;
4181            } catch (IOException e) {
4182                Slog.w(TAG, e);
4183            }
4184            if (observer != null) {
4185                try {
4186                    observer.onRemoveCompleted(null, success);
4187                } catch (RemoteException e) {
4188                    Slog.w(TAG, e);
4189                }
4190            }
4191        });
4192    }
4193
4194    @Override
4195    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4196            final int storageFlags, final IntentSender pi) {
4197        mContext.enforceCallingOrSelfPermission(
4198                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4199        mHandler.post(() -> {
4200            boolean success = false;
4201            try {
4202                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4203                success = true;
4204            } catch (IOException e) {
4205                Slog.w(TAG, e);
4206            }
4207            if (pi != null) {
4208                try {
4209                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4210                } catch (SendIntentException e) {
4211                    Slog.w(TAG, e);
4212                }
4213            }
4214        });
4215    }
4216
4217    /**
4218     * Blocking call to clear various types of cached data across the system
4219     * until the requested bytes are available.
4220     */
4221    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4222        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4223        final File file = storage.findPathForUuid(volumeUuid);
4224        if (file.getUsableSpace() >= bytes) return;
4225
4226        if (ENABLE_FREE_CACHE_V2) {
4227            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4228                    volumeUuid);
4229            final boolean aggressive = (storageFlags
4230                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4231            final boolean defyReserved = (storageFlags
4232                    & StorageManager.FLAG_ALLOCATE_DEFY_RESERVED) != 0;
4233            final long reservedBytes = (aggressive || defyReserved) ? 0
4234                    : storage.getStorageCacheBytes(file);
4235
4236            // 1. Pre-flight to determine if we have any chance to succeed
4237            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4238            if (internalVolume && (aggressive || SystemProperties
4239                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4240                deletePreloadsFileCache();
4241                if (file.getUsableSpace() >= bytes) return;
4242            }
4243
4244            // 3. Consider parsed APK data (aggressive only)
4245            if (internalVolume && aggressive) {
4246                FileUtils.deleteContents(mCacheDir);
4247                if (file.getUsableSpace() >= bytes) return;
4248            }
4249
4250            // 4. Consider cached app data (above quotas)
4251            try {
4252                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4253                        Installer.FLAG_FREE_CACHE_V2);
4254            } catch (InstallerException ignored) {
4255            }
4256            if (file.getUsableSpace() >= bytes) return;
4257
4258            // 5. Consider shared libraries with refcount=0 and age>min cache period
4259            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4260                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4261                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4262                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4263                return;
4264            }
4265
4266            // 6. Consider dexopt output (aggressive only)
4267            // TODO: Implement
4268
4269            // 7. Consider installed instant apps unused longer than min cache period
4270            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4271                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4272                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4273                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4274                return;
4275            }
4276
4277            // 8. Consider cached app data (below quotas)
4278            try {
4279                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4280                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4281            } catch (InstallerException ignored) {
4282            }
4283            if (file.getUsableSpace() >= bytes) return;
4284
4285            // 9. Consider DropBox entries
4286            // TODO: Implement
4287
4288            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4289            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4290                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4291                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4292                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4293                return;
4294            }
4295        } else {
4296            try {
4297                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4298            } catch (InstallerException ignored) {
4299            }
4300            if (file.getUsableSpace() >= bytes) return;
4301        }
4302
4303        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4304    }
4305
4306    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4307            throws IOException {
4308        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4309        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4310
4311        List<VersionedPackage> packagesToDelete = null;
4312        final long now = System.currentTimeMillis();
4313
4314        synchronized (mPackages) {
4315            final int[] allUsers = sUserManager.getUserIds();
4316            final int libCount = mSharedLibraries.size();
4317            for (int i = 0; i < libCount; i++) {
4318                final SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4319                if (versionedLib == null) {
4320                    continue;
4321                }
4322                final int versionCount = versionedLib.size();
4323                for (int j = 0; j < versionCount; j++) {
4324                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4325                    // Skip packages that are not static shared libs.
4326                    if (!libInfo.isStatic()) {
4327                        break;
4328                    }
4329                    // Important: We skip static shared libs used for some user since
4330                    // in such a case we need to keep the APK on the device. The check for
4331                    // a lib being used for any user is performed by the uninstall call.
4332                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4333                    // Resolve the package name - we use synthetic package names internally
4334                    final String internalPackageName = resolveInternalPackageNameLPr(
4335                            declaringPackage.getPackageName(), declaringPackage.getVersionCode());
4336                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4337                    // Skip unused static shared libs cached less than the min period
4338                    // to prevent pruning a lib needed by a subsequently installed package.
4339                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4340                        continue;
4341                    }
4342                    if (packagesToDelete == null) {
4343                        packagesToDelete = new ArrayList<>();
4344                    }
4345                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4346                            declaringPackage.getVersionCode()));
4347                }
4348            }
4349        }
4350
4351        if (packagesToDelete != null) {
4352            final int packageCount = packagesToDelete.size();
4353            for (int i = 0; i < packageCount; i++) {
4354                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4355                // Delete the package synchronously (will fail of the lib used for any user).
4356                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getVersionCode(),
4357                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4358                                == PackageManager.DELETE_SUCCEEDED) {
4359                    if (volume.getUsableSpace() >= neededSpace) {
4360                        return true;
4361                    }
4362                }
4363            }
4364        }
4365
4366        return false;
4367    }
4368
4369    /**
4370     * Update given flags based on encryption status of current user.
4371     */
4372    private int updateFlags(int flags, int userId) {
4373        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4374                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4375            // Caller expressed an explicit opinion about what encryption
4376            // aware/unaware components they want to see, so fall through and
4377            // give them what they want
4378        } else {
4379            // Caller expressed no opinion, so match based on user state
4380            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4381                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4382            } else {
4383                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4384            }
4385        }
4386        return flags;
4387    }
4388
4389    private UserManagerInternal getUserManagerInternal() {
4390        if (mUserManagerInternal == null) {
4391            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4392        }
4393        return mUserManagerInternal;
4394    }
4395
4396    private DeviceIdleController.LocalService getDeviceIdleController() {
4397        if (mDeviceIdleController == null) {
4398            mDeviceIdleController =
4399                    LocalServices.getService(DeviceIdleController.LocalService.class);
4400        }
4401        return mDeviceIdleController;
4402    }
4403
4404    /**
4405     * Update given flags when being used to request {@link PackageInfo}.
4406     */
4407    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4408        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4409        boolean triaged = true;
4410        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4411                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4412            // Caller is asking for component details, so they'd better be
4413            // asking for specific encryption matching behavior, or be triaged
4414            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4415                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4416                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4417                triaged = false;
4418            }
4419        }
4420        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4421                | PackageManager.MATCH_SYSTEM_ONLY
4422                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4423            triaged = false;
4424        }
4425        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4426            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
4427                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4428                    + Debug.getCallers(5));
4429        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4430                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4431            // If the caller wants all packages and has a restricted profile associated with it,
4432            // then match all users. This is to make sure that launchers that need to access work
4433            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4434            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4435            flags |= PackageManager.MATCH_ANY_USER;
4436        }
4437        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4438            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4439                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4440        }
4441        return updateFlags(flags, userId);
4442    }
4443
4444    /**
4445     * Update given flags when being used to request {@link ApplicationInfo}.
4446     */
4447    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4448        return updateFlagsForPackage(flags, userId, cookie);
4449    }
4450
4451    /**
4452     * Update given flags when being used to request {@link ComponentInfo}.
4453     */
4454    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4455        if (cookie instanceof Intent) {
4456            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4457                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4458            }
4459        }
4460
4461        boolean triaged = true;
4462        // Caller is asking for component details, so they'd better be
4463        // asking for specific encryption matching behavior, or be triaged
4464        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4465                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4466                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4467            triaged = false;
4468        }
4469        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4470            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4471                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4472        }
4473
4474        return updateFlags(flags, userId);
4475    }
4476
4477    /**
4478     * Update given intent when being used to request {@link ResolveInfo}.
4479     */
4480    private Intent updateIntentForResolve(Intent intent) {
4481        if (intent.getSelector() != null) {
4482            intent = intent.getSelector();
4483        }
4484        if (DEBUG_PREFERRED) {
4485            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4486        }
4487        return intent;
4488    }
4489
4490    /**
4491     * Update given flags when being used to request {@link ResolveInfo}.
4492     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4493     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4494     * flag set. However, this flag is only honoured in three circumstances:
4495     * <ul>
4496     * <li>when called from a system process</li>
4497     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4498     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4499     * action and a {@code android.intent.category.BROWSABLE} category</li>
4500     * </ul>
4501     */
4502    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4503        return updateFlagsForResolve(flags, userId, intent, callingUid,
4504                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4505    }
4506    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4507            boolean wantInstantApps) {
4508        return updateFlagsForResolve(flags, userId, intent, callingUid,
4509                wantInstantApps, false /*onlyExposedExplicitly*/);
4510    }
4511    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4512            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4513        // Safe mode means we shouldn't match any third-party components
4514        if (mSafeMode) {
4515            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4516        }
4517        if (getInstantAppPackageName(callingUid) != null) {
4518            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4519            if (onlyExposedExplicitly) {
4520                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4521            }
4522            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4523            flags |= PackageManager.MATCH_INSTANT;
4524        } else {
4525            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4526            final boolean allowMatchInstant =
4527                    (wantInstantApps
4528                            && Intent.ACTION_VIEW.equals(intent.getAction())
4529                            && hasWebURI(intent))
4530                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4531            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4532                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4533            if (!allowMatchInstant) {
4534                flags &= ~PackageManager.MATCH_INSTANT;
4535            }
4536        }
4537        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4538    }
4539
4540    @Override
4541    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4542        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4543    }
4544
4545    /**
4546     * Important: The provided filterCallingUid is used exclusively to filter out activities
4547     * that can be seen based on user state. It's typically the original caller uid prior
4548     * to clearing. Because it can only be provided by trusted code, it's value can be
4549     * trusted and will be used as-is; unlike userId which will be validated by this method.
4550     */
4551    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4552            int filterCallingUid, int userId) {
4553        if (!sUserManager.exists(userId)) return null;
4554        flags = updateFlagsForComponent(flags, userId, component);
4555        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4556                false /* requireFullPermission */, false /* checkShell */, "get activity info");
4557        synchronized (mPackages) {
4558            PackageParser.Activity a = mActivities.mActivities.get(component);
4559
4560            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4561            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4562                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4563                if (ps == null) return null;
4564                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4565                    return null;
4566                }
4567                return PackageParser.generateActivityInfo(
4568                        a, flags, ps.readUserState(userId), userId);
4569            }
4570            if (mResolveComponentName.equals(component)) {
4571                return PackageParser.generateActivityInfo(
4572                        mResolveActivity, flags, new PackageUserState(), userId);
4573            }
4574        }
4575        return null;
4576    }
4577
4578    @Override
4579    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4580            String resolvedType) {
4581        synchronized (mPackages) {
4582            if (component.equals(mResolveComponentName)) {
4583                // The resolver supports EVERYTHING!
4584                return true;
4585            }
4586            final int callingUid = Binder.getCallingUid();
4587            final int callingUserId = UserHandle.getUserId(callingUid);
4588            PackageParser.Activity a = mActivities.mActivities.get(component);
4589            if (a == null) {
4590                return false;
4591            }
4592            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4593            if (ps == null) {
4594                return false;
4595            }
4596            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4597                return false;
4598            }
4599            for (int i=0; i<a.intents.size(); i++) {
4600                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4601                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4602                    return true;
4603                }
4604            }
4605            return false;
4606        }
4607    }
4608
4609    @Override
4610    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4611        if (!sUserManager.exists(userId)) return null;
4612        final int callingUid = Binder.getCallingUid();
4613        flags = updateFlagsForComponent(flags, userId, component);
4614        enforceCrossUserPermission(callingUid, userId,
4615                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4616        synchronized (mPackages) {
4617            PackageParser.Activity a = mReceivers.mActivities.get(component);
4618            if (DEBUG_PACKAGE_INFO) Log.v(
4619                TAG, "getReceiverInfo " + component + ": " + a);
4620            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4621                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4622                if (ps == null) return null;
4623                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4624                    return null;
4625                }
4626                return PackageParser.generateActivityInfo(
4627                        a, flags, ps.readUserState(userId), userId);
4628            }
4629        }
4630        return null;
4631    }
4632
4633    @Override
4634    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4635            int flags, int userId) {
4636        if (!sUserManager.exists(userId)) return null;
4637        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4638        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4639            return null;
4640        }
4641
4642        flags = updateFlagsForPackage(flags, userId, null);
4643
4644        final boolean canSeeStaticLibraries =
4645                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4646                        == PERMISSION_GRANTED
4647                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4648                        == PERMISSION_GRANTED
4649                || canRequestPackageInstallsInternal(packageName,
4650                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
4651                        false  /* throwIfPermNotDeclared*/)
4652                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4653                        == PERMISSION_GRANTED;
4654
4655        synchronized (mPackages) {
4656            List<SharedLibraryInfo> result = null;
4657
4658            final int libCount = mSharedLibraries.size();
4659            for (int i = 0; i < libCount; i++) {
4660                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4661                if (versionedLib == null) {
4662                    continue;
4663                }
4664
4665                final int versionCount = versionedLib.size();
4666                for (int j = 0; j < versionCount; j++) {
4667                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4668                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4669                        break;
4670                    }
4671                    final long identity = Binder.clearCallingIdentity();
4672                    try {
4673                        PackageInfo packageInfo = getPackageInfoVersioned(
4674                                libInfo.getDeclaringPackage(), flags
4675                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
4676                        if (packageInfo == null) {
4677                            continue;
4678                        }
4679                    } finally {
4680                        Binder.restoreCallingIdentity(identity);
4681                    }
4682
4683                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4684                            libInfo.getVersion(), libInfo.getType(),
4685                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
4686                            flags, userId));
4687
4688                    if (result == null) {
4689                        result = new ArrayList<>();
4690                    }
4691                    result.add(resLibInfo);
4692                }
4693            }
4694
4695            return result != null ? new ParceledListSlice<>(result) : null;
4696        }
4697    }
4698
4699    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4700            SharedLibraryInfo libInfo, int flags, int userId) {
4701        List<VersionedPackage> versionedPackages = null;
4702        final int packageCount = mSettings.mPackages.size();
4703        for (int i = 0; i < packageCount; i++) {
4704            PackageSetting ps = mSettings.mPackages.valueAt(i);
4705
4706            if (ps == null) {
4707                continue;
4708            }
4709
4710            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4711                continue;
4712            }
4713
4714            final String libName = libInfo.getName();
4715            if (libInfo.isStatic()) {
4716                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4717                if (libIdx < 0) {
4718                    continue;
4719                }
4720                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
4721                    continue;
4722                }
4723                if (versionedPackages == null) {
4724                    versionedPackages = new ArrayList<>();
4725                }
4726                // If the dependent is a static shared lib, use the public package name
4727                String dependentPackageName = ps.name;
4728                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4729                    dependentPackageName = ps.pkg.manifestPackageName;
4730                }
4731                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
4732            } else if (ps.pkg != null) {
4733                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
4734                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
4735                    if (versionedPackages == null) {
4736                        versionedPackages = new ArrayList<>();
4737                    }
4738                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
4739                }
4740            }
4741        }
4742
4743        return versionedPackages;
4744    }
4745
4746    @Override
4747    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
4748        if (!sUserManager.exists(userId)) return null;
4749        final int callingUid = Binder.getCallingUid();
4750        flags = updateFlagsForComponent(flags, userId, component);
4751        enforceCrossUserPermission(callingUid, userId,
4752                false /* requireFullPermission */, false /* checkShell */, "get service info");
4753        synchronized (mPackages) {
4754            PackageParser.Service s = mServices.mServices.get(component);
4755            if (DEBUG_PACKAGE_INFO) Log.v(
4756                TAG, "getServiceInfo " + component + ": " + s);
4757            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
4758                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4759                if (ps == null) return null;
4760                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
4761                    return null;
4762                }
4763                return PackageParser.generateServiceInfo(
4764                        s, flags, ps.readUserState(userId), userId);
4765            }
4766        }
4767        return null;
4768    }
4769
4770    @Override
4771    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
4772        if (!sUserManager.exists(userId)) return null;
4773        final int callingUid = Binder.getCallingUid();
4774        flags = updateFlagsForComponent(flags, userId, component);
4775        enforceCrossUserPermission(callingUid, userId,
4776                false /* requireFullPermission */, false /* checkShell */, "get provider info");
4777        synchronized (mPackages) {
4778            PackageParser.Provider p = mProviders.mProviders.get(component);
4779            if (DEBUG_PACKAGE_INFO) Log.v(
4780                TAG, "getProviderInfo " + component + ": " + p);
4781            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
4782                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4783                if (ps == null) return null;
4784                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
4785                    return null;
4786                }
4787                return PackageParser.generateProviderInfo(
4788                        p, flags, ps.readUserState(userId), userId);
4789            }
4790        }
4791        return null;
4792    }
4793
4794    @Override
4795    public String[] getSystemSharedLibraryNames() {
4796        // allow instant applications
4797        synchronized (mPackages) {
4798            Set<String> libs = null;
4799            final int libCount = mSharedLibraries.size();
4800            for (int i = 0; i < libCount; i++) {
4801                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4802                if (versionedLib == null) {
4803                    continue;
4804                }
4805                final int versionCount = versionedLib.size();
4806                for (int j = 0; j < versionCount; j++) {
4807                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
4808                    if (!libEntry.info.isStatic()) {
4809                        if (libs == null) {
4810                            libs = new ArraySet<>();
4811                        }
4812                        libs.add(libEntry.info.getName());
4813                        break;
4814                    }
4815                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
4816                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
4817                            UserHandle.getUserId(Binder.getCallingUid()),
4818                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
4819                        if (libs == null) {
4820                            libs = new ArraySet<>();
4821                        }
4822                        libs.add(libEntry.info.getName());
4823                        break;
4824                    }
4825                }
4826            }
4827
4828            if (libs != null) {
4829                String[] libsArray = new String[libs.size()];
4830                libs.toArray(libsArray);
4831                return libsArray;
4832            }
4833
4834            return null;
4835        }
4836    }
4837
4838    @Override
4839    public @NonNull String getServicesSystemSharedLibraryPackageName() {
4840        // allow instant applications
4841        synchronized (mPackages) {
4842            return mServicesSystemSharedLibraryPackageName;
4843        }
4844    }
4845
4846    @Override
4847    public @NonNull String getSharedSystemSharedLibraryPackageName() {
4848        // allow instant applications
4849        synchronized (mPackages) {
4850            return mSharedSystemSharedLibraryPackageName;
4851        }
4852    }
4853
4854    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
4855        for (int i = userList.length - 1; i >= 0; --i) {
4856            final int userId = userList[i];
4857            // don't add instant app to the list of updates
4858            if (pkgSetting.getInstantApp(userId)) {
4859                continue;
4860            }
4861            SparseArray<String> changedPackages = mChangedPackages.get(userId);
4862            if (changedPackages == null) {
4863                changedPackages = new SparseArray<>();
4864                mChangedPackages.put(userId, changedPackages);
4865            }
4866            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
4867            if (sequenceNumbers == null) {
4868                sequenceNumbers = new HashMap<>();
4869                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
4870            }
4871            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
4872            if (sequenceNumber != null) {
4873                changedPackages.remove(sequenceNumber);
4874            }
4875            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
4876            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
4877        }
4878        mChangedPackagesSequenceNumber++;
4879    }
4880
4881    @Override
4882    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
4883        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4884            return null;
4885        }
4886        synchronized (mPackages) {
4887            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
4888                return null;
4889            }
4890            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
4891            if (changedPackages == null) {
4892                return null;
4893            }
4894            final List<String> packageNames =
4895                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
4896            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
4897                final String packageName = changedPackages.get(i);
4898                if (packageName != null) {
4899                    packageNames.add(packageName);
4900                }
4901            }
4902            return packageNames.isEmpty()
4903                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
4904        }
4905    }
4906
4907    @Override
4908    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
4909        // allow instant applications
4910        ArrayList<FeatureInfo> res;
4911        synchronized (mAvailableFeatures) {
4912            res = new ArrayList<>(mAvailableFeatures.size() + 1);
4913            res.addAll(mAvailableFeatures.values());
4914        }
4915        final FeatureInfo fi = new FeatureInfo();
4916        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
4917                FeatureInfo.GL_ES_VERSION_UNDEFINED);
4918        res.add(fi);
4919
4920        return new ParceledListSlice<>(res);
4921    }
4922
4923    @Override
4924    public boolean hasSystemFeature(String name, int version) {
4925        // allow instant applications
4926        synchronized (mAvailableFeatures) {
4927            final FeatureInfo feat = mAvailableFeatures.get(name);
4928            if (feat == null) {
4929                return false;
4930            } else {
4931                return feat.version >= version;
4932            }
4933        }
4934    }
4935
4936    @Override
4937    public int checkPermission(String permName, String pkgName, int userId) {
4938        if (!sUserManager.exists(userId)) {
4939            return PackageManager.PERMISSION_DENIED;
4940        }
4941        final int callingUid = Binder.getCallingUid();
4942
4943        synchronized (mPackages) {
4944            final PackageParser.Package p = mPackages.get(pkgName);
4945            if (p != null && p.mExtras != null) {
4946                final PackageSetting ps = (PackageSetting) p.mExtras;
4947                if (filterAppAccessLPr(ps, callingUid, userId)) {
4948                    return PackageManager.PERMISSION_DENIED;
4949                }
4950                final boolean instantApp = ps.getInstantApp(userId);
4951                final PermissionsState permissionsState = ps.getPermissionsState();
4952                if (permissionsState.hasPermission(permName, userId)) {
4953                    if (instantApp) {
4954                        BasePermission bp = mSettings.mPermissions.get(permName);
4955                        if (bp != null && bp.isInstant()) {
4956                            return PackageManager.PERMISSION_GRANTED;
4957                        }
4958                    } else {
4959                        return PackageManager.PERMISSION_GRANTED;
4960                    }
4961                }
4962                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
4963                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
4964                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
4965                    return PackageManager.PERMISSION_GRANTED;
4966                }
4967            }
4968        }
4969
4970        return PackageManager.PERMISSION_DENIED;
4971    }
4972
4973    @Override
4974    public int checkUidPermission(String permName, int uid) {
4975        final int callingUid = Binder.getCallingUid();
4976        final int callingUserId = UserHandle.getUserId(callingUid);
4977        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
4978        final boolean isUidInstantApp = getInstantAppPackageName(uid) != null;
4979        final int userId = UserHandle.getUserId(uid);
4980        if (!sUserManager.exists(userId)) {
4981            return PackageManager.PERMISSION_DENIED;
4982        }
4983
4984        synchronized (mPackages) {
4985            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4986            if (obj != null) {
4987                if (obj instanceof SharedUserSetting) {
4988                    if (isCallerInstantApp) {
4989                        return PackageManager.PERMISSION_DENIED;
4990                    }
4991                } else if (obj instanceof PackageSetting) {
4992                    final PackageSetting ps = (PackageSetting) obj;
4993                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
4994                        return PackageManager.PERMISSION_DENIED;
4995                    }
4996                }
4997                final SettingBase settingBase = (SettingBase) obj;
4998                final PermissionsState permissionsState = settingBase.getPermissionsState();
4999                if (permissionsState.hasPermission(permName, userId)) {
5000                    if (isUidInstantApp) {
5001                        BasePermission bp = mSettings.mPermissions.get(permName);
5002                        if (bp != null && bp.isInstant()) {
5003                            return PackageManager.PERMISSION_GRANTED;
5004                        }
5005                    } else {
5006                        return PackageManager.PERMISSION_GRANTED;
5007                    }
5008                }
5009                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5010                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5011                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5012                    return PackageManager.PERMISSION_GRANTED;
5013                }
5014            } else {
5015                ArraySet<String> perms = mSystemPermissions.get(uid);
5016                if (perms != null) {
5017                    if (perms.contains(permName)) {
5018                        return PackageManager.PERMISSION_GRANTED;
5019                    }
5020                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
5021                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
5022                        return PackageManager.PERMISSION_GRANTED;
5023                    }
5024                }
5025            }
5026        }
5027
5028        return PackageManager.PERMISSION_DENIED;
5029    }
5030
5031    @Override
5032    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5033        if (UserHandle.getCallingUserId() != userId) {
5034            mContext.enforceCallingPermission(
5035                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5036                    "isPermissionRevokedByPolicy for user " + userId);
5037        }
5038
5039        if (checkPermission(permission, packageName, userId)
5040                == PackageManager.PERMISSION_GRANTED) {
5041            return false;
5042        }
5043
5044        final int callingUid = Binder.getCallingUid();
5045        if (getInstantAppPackageName(callingUid) != null) {
5046            if (!isCallerSameApp(packageName, callingUid)) {
5047                return false;
5048            }
5049        } else {
5050            if (isInstantApp(packageName, userId)) {
5051                return false;
5052            }
5053        }
5054
5055        final long identity = Binder.clearCallingIdentity();
5056        try {
5057            final int flags = getPermissionFlags(permission, packageName, userId);
5058            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5059        } finally {
5060            Binder.restoreCallingIdentity(identity);
5061        }
5062    }
5063
5064    @Override
5065    public String getPermissionControllerPackageName() {
5066        synchronized (mPackages) {
5067            return mRequiredInstallerPackage;
5068        }
5069    }
5070
5071    /**
5072     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
5073     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
5074     * @param checkShell whether to prevent shell from access if there's a debugging restriction
5075     * @param message the message to log on security exception
5076     */
5077    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
5078            boolean checkShell, String message) {
5079        if (userId < 0) {
5080            throw new IllegalArgumentException("Invalid userId " + userId);
5081        }
5082        if (checkShell) {
5083            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
5084        }
5085        if (userId == UserHandle.getUserId(callingUid)) return;
5086        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5087            if (requireFullPermission) {
5088                mContext.enforceCallingOrSelfPermission(
5089                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5090            } else {
5091                try {
5092                    mContext.enforceCallingOrSelfPermission(
5093                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5094                } catch (SecurityException se) {
5095                    mContext.enforceCallingOrSelfPermission(
5096                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
5097                }
5098            }
5099        }
5100    }
5101
5102    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
5103        if (callingUid == Process.SHELL_UID) {
5104            if (userHandle >= 0
5105                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
5106                throw new SecurityException("Shell does not have permission to access user "
5107                        + userHandle);
5108            } else if (userHandle < 0) {
5109                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
5110                        + Debug.getCallers(3));
5111            }
5112        }
5113    }
5114
5115    private BasePermission findPermissionTreeLP(String permName) {
5116        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
5117            if (permName.startsWith(bp.name) &&
5118                    permName.length() > bp.name.length() &&
5119                    permName.charAt(bp.name.length()) == '.') {
5120                return bp;
5121            }
5122        }
5123        return null;
5124    }
5125
5126    private BasePermission checkPermissionTreeLP(String permName) {
5127        if (permName != null) {
5128            BasePermission bp = findPermissionTreeLP(permName);
5129            if (bp != null) {
5130                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
5131                    return bp;
5132                }
5133                throw new SecurityException("Calling uid "
5134                        + Binder.getCallingUid()
5135                        + " is not allowed to add to permission tree "
5136                        + bp.name + " owned by uid " + bp.uid);
5137            }
5138        }
5139        throw new SecurityException("No permission tree found for " + permName);
5140    }
5141
5142    static boolean compareStrings(CharSequence s1, CharSequence s2) {
5143        if (s1 == null) {
5144            return s2 == null;
5145        }
5146        if (s2 == null) {
5147            return false;
5148        }
5149        if (s1.getClass() != s2.getClass()) {
5150            return false;
5151        }
5152        return s1.equals(s2);
5153    }
5154
5155    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
5156        if (pi1.icon != pi2.icon) return false;
5157        if (pi1.logo != pi2.logo) return false;
5158        if (pi1.protectionLevel != pi2.protectionLevel) return false;
5159        if (!compareStrings(pi1.name, pi2.name)) return false;
5160        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
5161        // We'll take care of setting this one.
5162        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
5163        // These are not currently stored in settings.
5164        //if (!compareStrings(pi1.group, pi2.group)) return false;
5165        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
5166        //if (pi1.labelRes != pi2.labelRes) return false;
5167        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
5168        return true;
5169    }
5170
5171    int permissionInfoFootprint(PermissionInfo info) {
5172        int size = info.name.length();
5173        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
5174        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
5175        return size;
5176    }
5177
5178    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
5179        int size = 0;
5180        for (BasePermission perm : mSettings.mPermissions.values()) {
5181            if (perm.uid == tree.uid) {
5182                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
5183            }
5184        }
5185        return size;
5186    }
5187
5188    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
5189        // We calculate the max size of permissions defined by this uid and throw
5190        // if that plus the size of 'info' would exceed our stated maximum.
5191        if (tree.uid != Process.SYSTEM_UID) {
5192            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
5193            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
5194                throw new SecurityException("Permission tree size cap exceeded");
5195            }
5196        }
5197    }
5198
5199    boolean addPermissionLocked(PermissionInfo info, boolean async) {
5200        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5201            throw new SecurityException("Instant apps can't add permissions");
5202        }
5203        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
5204            throw new SecurityException("Label must be specified in permission");
5205        }
5206        BasePermission tree = checkPermissionTreeLP(info.name);
5207        BasePermission bp = mSettings.mPermissions.get(info.name);
5208        boolean added = bp == null;
5209        boolean changed = true;
5210        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
5211        if (added) {
5212            enforcePermissionCapLocked(info, tree);
5213            bp = new BasePermission(info.name, tree.sourcePackage,
5214                    BasePermission.TYPE_DYNAMIC);
5215        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
5216            throw new SecurityException(
5217                    "Not allowed to modify non-dynamic permission "
5218                    + info.name);
5219        } else {
5220            if (bp.protectionLevel == fixedLevel
5221                    && bp.perm.owner.equals(tree.perm.owner)
5222                    && bp.uid == tree.uid
5223                    && comparePermissionInfos(bp.perm.info, info)) {
5224                changed = false;
5225            }
5226        }
5227        bp.protectionLevel = fixedLevel;
5228        info = new PermissionInfo(info);
5229        info.protectionLevel = fixedLevel;
5230        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
5231        bp.perm.info.packageName = tree.perm.info.packageName;
5232        bp.uid = tree.uid;
5233        if (added) {
5234            mSettings.mPermissions.put(info.name, bp);
5235        }
5236        if (changed) {
5237            if (!async) {
5238                mSettings.writeLPr();
5239            } else {
5240                scheduleWriteSettingsLocked();
5241            }
5242        }
5243        return added;
5244    }
5245
5246    @Override
5247    public boolean addPermission(PermissionInfo info) {
5248        synchronized (mPackages) {
5249            return addPermissionLocked(info, false);
5250        }
5251    }
5252
5253    @Override
5254    public boolean addPermissionAsync(PermissionInfo info) {
5255        synchronized (mPackages) {
5256            return addPermissionLocked(info, true);
5257        }
5258    }
5259
5260    @Override
5261    public void removePermission(String name) {
5262        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5263            throw new SecurityException("Instant applications don't have access to this method");
5264        }
5265        synchronized (mPackages) {
5266            checkPermissionTreeLP(name);
5267            BasePermission bp = mSettings.mPermissions.get(name);
5268            if (bp != null) {
5269                if (bp.type != BasePermission.TYPE_DYNAMIC) {
5270                    throw new SecurityException(
5271                            "Not allowed to modify non-dynamic permission "
5272                            + name);
5273                }
5274                mSettings.mPermissions.remove(name);
5275                mSettings.writeLPr();
5276            }
5277        }
5278    }
5279
5280    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(
5281            PackageParser.Package pkg, BasePermission bp) {
5282        int index = pkg.requestedPermissions.indexOf(bp.name);
5283        if (index == -1) {
5284            throw new SecurityException("Package " + pkg.packageName
5285                    + " has not requested permission " + bp.name);
5286        }
5287        if (!bp.isRuntime() && !bp.isDevelopment()) {
5288            throw new SecurityException("Permission " + bp.name
5289                    + " is not a changeable permission type");
5290        }
5291    }
5292
5293    @Override
5294    public void grantRuntimePermission(String packageName, String name, final int userId) {
5295        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5296    }
5297
5298    private void grantRuntimePermission(String packageName, String name, final int userId,
5299            boolean overridePolicy) {
5300        if (!sUserManager.exists(userId)) {
5301            Log.e(TAG, "No such user:" + userId);
5302            return;
5303        }
5304        final int callingUid = Binder.getCallingUid();
5305
5306        mContext.enforceCallingOrSelfPermission(
5307                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
5308                "grantRuntimePermission");
5309
5310        enforceCrossUserPermission(callingUid, userId,
5311                true /* requireFullPermission */, true /* checkShell */,
5312                "grantRuntimePermission");
5313
5314        final int uid;
5315        final PackageSetting ps;
5316
5317        synchronized (mPackages) {
5318            final PackageParser.Package pkg = mPackages.get(packageName);
5319            if (pkg == null) {
5320                throw new IllegalArgumentException("Unknown package: " + packageName);
5321            }
5322            final BasePermission bp = mSettings.mPermissions.get(name);
5323            if (bp == null) {
5324                throw new IllegalArgumentException("Unknown permission: " + name);
5325            }
5326            ps = (PackageSetting) pkg.mExtras;
5327            if (ps == null
5328                    || filterAppAccessLPr(ps, callingUid, userId)) {
5329                throw new IllegalArgumentException("Unknown package: " + packageName);
5330            }
5331
5332            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5333
5334            // If a permission review is required for legacy apps we represent
5335            // their permissions as always granted runtime ones since we need
5336            // to keep the review required permission flag per user while an
5337            // install permission's state is shared across all users.
5338            if (mPermissionReviewRequired
5339                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5340                    && bp.isRuntime()) {
5341                return;
5342            }
5343
5344            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
5345
5346            final PermissionsState permissionsState = ps.getPermissionsState();
5347
5348            final int flags = permissionsState.getPermissionFlags(name, userId);
5349            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5350                throw new SecurityException("Cannot grant system fixed permission "
5351                        + name + " for package " + packageName);
5352            }
5353            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5354                throw new SecurityException("Cannot grant policy fixed permission "
5355                        + name + " for package " + packageName);
5356            }
5357
5358            if (bp.isDevelopment()) {
5359                // Development permissions must be handled specially, since they are not
5360                // normal runtime permissions.  For now they apply to all users.
5361                if (permissionsState.grantInstallPermission(bp) !=
5362                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5363                    scheduleWriteSettingsLocked();
5364                }
5365                return;
5366            }
5367
5368            if (ps.getInstantApp(userId) && !bp.isInstant()) {
5369                throw new SecurityException("Cannot grant non-ephemeral permission"
5370                        + name + " for package " + packageName);
5371            }
5372
5373            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
5374                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
5375                return;
5376            }
5377
5378            final int result = permissionsState.grantRuntimePermission(bp, userId);
5379            switch (result) {
5380                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
5381                    return;
5382                }
5383
5384                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
5385                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5386                    mHandler.post(new Runnable() {
5387                        @Override
5388                        public void run() {
5389                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
5390                        }
5391                    });
5392                }
5393                break;
5394            }
5395
5396            if (bp.isRuntime()) {
5397                logPermissionGranted(mContext, name, packageName);
5398            }
5399
5400            mOnPermissionChangeListeners.onPermissionsChanged(uid);
5401
5402            // Not critical if that is lost - app has to request again.
5403            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5404        }
5405
5406        // Only need to do this if user is initialized. Otherwise it's a new user
5407        // and there are no processes running as the user yet and there's no need
5408        // to make an expensive call to remount processes for the changed permissions.
5409        if (READ_EXTERNAL_STORAGE.equals(name)
5410                || WRITE_EXTERNAL_STORAGE.equals(name)) {
5411            final long token = Binder.clearCallingIdentity();
5412            try {
5413                if (sUserManager.isInitialized(userId)) {
5414                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
5415                            StorageManagerInternal.class);
5416                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
5417                }
5418            } finally {
5419                Binder.restoreCallingIdentity(token);
5420            }
5421        }
5422    }
5423
5424    @Override
5425    public void revokeRuntimePermission(String packageName, String name, int userId) {
5426        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5427    }
5428
5429    private void revokeRuntimePermission(String packageName, String name, int userId,
5430            boolean overridePolicy) {
5431        if (!sUserManager.exists(userId)) {
5432            Log.e(TAG, "No such user:" + userId);
5433            return;
5434        }
5435
5436        mContext.enforceCallingOrSelfPermission(
5437                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5438                "revokeRuntimePermission");
5439
5440        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5441                true /* requireFullPermission */, true /* checkShell */,
5442                "revokeRuntimePermission");
5443
5444        final int appId;
5445
5446        synchronized (mPackages) {
5447            final PackageParser.Package pkg = mPackages.get(packageName);
5448            if (pkg == null) {
5449                throw new IllegalArgumentException("Unknown package: " + packageName);
5450            }
5451            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5452            if (ps == null
5453                    || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
5454                throw new IllegalArgumentException("Unknown package: " + packageName);
5455            }
5456            final BasePermission bp = mSettings.mPermissions.get(name);
5457            if (bp == null) {
5458                throw new IllegalArgumentException("Unknown permission: " + name);
5459            }
5460
5461            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5462
5463            // If a permission review is required for legacy apps we represent
5464            // their permissions as always granted runtime ones since we need
5465            // to keep the review required permission flag per user while an
5466            // install permission's state is shared across all users.
5467            if (mPermissionReviewRequired
5468                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5469                    && bp.isRuntime()) {
5470                return;
5471            }
5472
5473            final PermissionsState permissionsState = ps.getPermissionsState();
5474
5475            final int flags = permissionsState.getPermissionFlags(name, userId);
5476            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5477                throw new SecurityException("Cannot revoke system fixed permission "
5478                        + name + " for package " + packageName);
5479            }
5480            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5481                throw new SecurityException("Cannot revoke policy fixed permission "
5482                        + name + " for package " + packageName);
5483            }
5484
5485            if (bp.isDevelopment()) {
5486                // Development permissions must be handled specially, since they are not
5487                // normal runtime permissions.  For now they apply to all users.
5488                if (permissionsState.revokeInstallPermission(bp) !=
5489                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5490                    scheduleWriteSettingsLocked();
5491                }
5492                return;
5493            }
5494
5495            if (permissionsState.revokeRuntimePermission(bp, userId) ==
5496                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
5497                return;
5498            }
5499
5500            if (bp.isRuntime()) {
5501                logPermissionRevoked(mContext, name, packageName);
5502            }
5503
5504            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
5505
5506            // Critical, after this call app should never have the permission.
5507            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
5508
5509            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5510        }
5511
5512        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
5513    }
5514
5515    /**
5516     * Get the first event id for the permission.
5517     *
5518     * <p>There are four events for each permission: <ul>
5519     *     <li>Request permission: first id + 0</li>
5520     *     <li>Grant permission: first id + 1</li>
5521     *     <li>Request for permission denied: first id + 2</li>
5522     *     <li>Revoke permission: first id + 3</li>
5523     * </ul></p>
5524     *
5525     * @param name name of the permission
5526     *
5527     * @return The first event id for the permission
5528     */
5529    private static int getBaseEventId(@NonNull String name) {
5530        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
5531
5532        if (eventIdIndex == -1) {
5533            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
5534                    || "user".equals(Build.TYPE)) {
5535                Log.i(TAG, "Unknown permission " + name);
5536
5537                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
5538            } else {
5539                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
5540                //
5541                // Also update
5542                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
5543                // - metrics_constants.proto
5544                throw new IllegalStateException("Unknown permission " + name);
5545            }
5546        }
5547
5548        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
5549    }
5550
5551    /**
5552     * Log that a permission was revoked.
5553     *
5554     * @param context Context of the caller
5555     * @param name name of the permission
5556     * @param packageName package permission if for
5557     */
5558    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
5559            @NonNull String packageName) {
5560        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
5561    }
5562
5563    /**
5564     * Log that a permission request was granted.
5565     *
5566     * @param context Context of the caller
5567     * @param name name of the permission
5568     * @param packageName package permission if for
5569     */
5570    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
5571            @NonNull String packageName) {
5572        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
5573    }
5574
5575    @Override
5576    public void resetRuntimePermissions() {
5577        mContext.enforceCallingOrSelfPermission(
5578                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5579                "revokeRuntimePermission");
5580
5581        int callingUid = Binder.getCallingUid();
5582        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5583            mContext.enforceCallingOrSelfPermission(
5584                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5585                    "resetRuntimePermissions");
5586        }
5587
5588        synchronized (mPackages) {
5589            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
5590            for (int userId : UserManagerService.getInstance().getUserIds()) {
5591                final int packageCount = mPackages.size();
5592                for (int i = 0; i < packageCount; i++) {
5593                    PackageParser.Package pkg = mPackages.valueAt(i);
5594                    if (!(pkg.mExtras instanceof PackageSetting)) {
5595                        continue;
5596                    }
5597                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5598                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5599                }
5600            }
5601        }
5602    }
5603
5604    @Override
5605    public int getPermissionFlags(String name, String packageName, int userId) {
5606        if (!sUserManager.exists(userId)) {
5607            return 0;
5608        }
5609
5610        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
5611
5612        final int callingUid = Binder.getCallingUid();
5613        enforceCrossUserPermission(callingUid, userId,
5614                true /* requireFullPermission */, false /* checkShell */,
5615                "getPermissionFlags");
5616
5617        synchronized (mPackages) {
5618            final PackageParser.Package pkg = mPackages.get(packageName);
5619            if (pkg == null) {
5620                return 0;
5621            }
5622            final BasePermission bp = mSettings.mPermissions.get(name);
5623            if (bp == null) {
5624                return 0;
5625            }
5626            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5627            if (ps == null
5628                    || filterAppAccessLPr(ps, callingUid, userId)) {
5629                return 0;
5630            }
5631            PermissionsState permissionsState = ps.getPermissionsState();
5632            return permissionsState.getPermissionFlags(name, userId);
5633        }
5634    }
5635
5636    @Override
5637    public void updatePermissionFlags(String name, String packageName, int flagMask,
5638            int flagValues, int userId) {
5639        if (!sUserManager.exists(userId)) {
5640            return;
5641        }
5642
5643        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
5644
5645        final int callingUid = Binder.getCallingUid();
5646        enforceCrossUserPermission(callingUid, userId,
5647                true /* requireFullPermission */, true /* checkShell */,
5648                "updatePermissionFlags");
5649
5650        // Only the system can change these flags and nothing else.
5651        if (getCallingUid() != Process.SYSTEM_UID) {
5652            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5653            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5654            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5655            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5656            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
5657        }
5658
5659        synchronized (mPackages) {
5660            final PackageParser.Package pkg = mPackages.get(packageName);
5661            if (pkg == null) {
5662                throw new IllegalArgumentException("Unknown package: " + packageName);
5663            }
5664            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5665            if (ps == null
5666                    || filterAppAccessLPr(ps, callingUid, userId)) {
5667                throw new IllegalArgumentException("Unknown package: " + packageName);
5668            }
5669
5670            final BasePermission bp = mSettings.mPermissions.get(name);
5671            if (bp == null) {
5672                throw new IllegalArgumentException("Unknown permission: " + name);
5673            }
5674
5675            PermissionsState permissionsState = ps.getPermissionsState();
5676
5677            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
5678
5679            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
5680                // Install and runtime permissions are stored in different places,
5681                // so figure out what permission changed and persist the change.
5682                if (permissionsState.getInstallPermissionState(name) != null) {
5683                    scheduleWriteSettingsLocked();
5684                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
5685                        || hadState) {
5686                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5687                }
5688            }
5689        }
5690    }
5691
5692    /**
5693     * Update the permission flags for all packages and runtime permissions of a user in order
5694     * to allow device or profile owner to remove POLICY_FIXED.
5695     */
5696    @Override
5697    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5698        if (!sUserManager.exists(userId)) {
5699            return;
5700        }
5701
5702        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
5703
5704        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5705                true /* requireFullPermission */, true /* checkShell */,
5706                "updatePermissionFlagsForAllApps");
5707
5708        // Only the system can change system fixed flags.
5709        if (getCallingUid() != Process.SYSTEM_UID) {
5710            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5711            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5712        }
5713
5714        synchronized (mPackages) {
5715            boolean changed = false;
5716            final int packageCount = mPackages.size();
5717            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
5718                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
5719                final PackageSetting ps = (PackageSetting) pkg.mExtras;
5720                if (ps == null) {
5721                    continue;
5722                }
5723                PermissionsState permissionsState = ps.getPermissionsState();
5724                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
5725                        userId, flagMask, flagValues);
5726            }
5727            if (changed) {
5728                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5729            }
5730        }
5731    }
5732
5733    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
5734        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
5735                != PackageManager.PERMISSION_GRANTED
5736            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
5737                != PackageManager.PERMISSION_GRANTED) {
5738            throw new SecurityException(message + " requires "
5739                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
5740                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
5741        }
5742    }
5743
5744    @Override
5745    public boolean shouldShowRequestPermissionRationale(String permissionName,
5746            String packageName, int userId) {
5747        if (UserHandle.getCallingUserId() != userId) {
5748            mContext.enforceCallingPermission(
5749                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5750                    "canShowRequestPermissionRationale for user " + userId);
5751        }
5752
5753        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5754        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5755            return false;
5756        }
5757
5758        if (checkPermission(permissionName, packageName, userId)
5759                == PackageManager.PERMISSION_GRANTED) {
5760            return false;
5761        }
5762
5763        final int flags;
5764
5765        final long identity = Binder.clearCallingIdentity();
5766        try {
5767            flags = getPermissionFlags(permissionName,
5768                    packageName, userId);
5769        } finally {
5770            Binder.restoreCallingIdentity(identity);
5771        }
5772
5773        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5774                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5775                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5776
5777        if ((flags & fixedFlags) != 0) {
5778            return false;
5779        }
5780
5781        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5782    }
5783
5784    @Override
5785    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5786        mContext.enforceCallingOrSelfPermission(
5787                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5788                "addOnPermissionsChangeListener");
5789
5790        synchronized (mPackages) {
5791            mOnPermissionChangeListeners.addListenerLocked(listener);
5792        }
5793    }
5794
5795    @Override
5796    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5797        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5798            throw new SecurityException("Instant applications don't have access to this method");
5799        }
5800        synchronized (mPackages) {
5801            mOnPermissionChangeListeners.removeListenerLocked(listener);
5802        }
5803    }
5804
5805    @Override
5806    public boolean isProtectedBroadcast(String actionName) {
5807        // allow instant applications
5808        synchronized (mPackages) {
5809            if (mProtectedBroadcasts.contains(actionName)) {
5810                return true;
5811            } else if (actionName != null) {
5812                // TODO: remove these terrible hacks
5813                if (actionName.startsWith("android.net.netmon.lingerExpired")
5814                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5815                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5816                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5817                    return true;
5818                }
5819            }
5820        }
5821        return false;
5822    }
5823
5824    @Override
5825    public int checkSignatures(String pkg1, String pkg2) {
5826        synchronized (mPackages) {
5827            final PackageParser.Package p1 = mPackages.get(pkg1);
5828            final PackageParser.Package p2 = mPackages.get(pkg2);
5829            if (p1 == null || p1.mExtras == null
5830                    || p2 == null || p2.mExtras == null) {
5831                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5832            }
5833            final int callingUid = Binder.getCallingUid();
5834            final int callingUserId = UserHandle.getUserId(callingUid);
5835            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
5836            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
5837            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
5838                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
5839                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5840            }
5841            return compareSignatures(p1.mSignatures, p2.mSignatures);
5842        }
5843    }
5844
5845    @Override
5846    public int checkUidSignatures(int uid1, int uid2) {
5847        final int callingUid = Binder.getCallingUid();
5848        final int callingUserId = UserHandle.getUserId(callingUid);
5849        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5850        // Map to base uids.
5851        uid1 = UserHandle.getAppId(uid1);
5852        uid2 = UserHandle.getAppId(uid2);
5853        // reader
5854        synchronized (mPackages) {
5855            Signature[] s1;
5856            Signature[] s2;
5857            Object obj = mSettings.getUserIdLPr(uid1);
5858            if (obj != null) {
5859                if (obj instanceof SharedUserSetting) {
5860                    if (isCallerInstantApp) {
5861                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5862                    }
5863                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
5864                } else if (obj instanceof PackageSetting) {
5865                    final PackageSetting ps = (PackageSetting) obj;
5866                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5867                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5868                    }
5869                    s1 = ps.signatures.mSignatures;
5870                } else {
5871                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5872                }
5873            } else {
5874                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5875            }
5876            obj = mSettings.getUserIdLPr(uid2);
5877            if (obj != null) {
5878                if (obj instanceof SharedUserSetting) {
5879                    if (isCallerInstantApp) {
5880                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5881                    }
5882                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
5883                } else if (obj instanceof PackageSetting) {
5884                    final PackageSetting ps = (PackageSetting) obj;
5885                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5886                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5887                    }
5888                    s2 = ps.signatures.mSignatures;
5889                } else {
5890                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5891                }
5892            } else {
5893                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5894            }
5895            return compareSignatures(s1, s2);
5896        }
5897    }
5898
5899    /**
5900     * This method should typically only be used when granting or revoking
5901     * permissions, since the app may immediately restart after this call.
5902     * <p>
5903     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5904     * guard your work against the app being relaunched.
5905     */
5906    private void killUid(int appId, int userId, String reason) {
5907        final long identity = Binder.clearCallingIdentity();
5908        try {
5909            IActivityManager am = ActivityManager.getService();
5910            if (am != null) {
5911                try {
5912                    am.killUid(appId, userId, reason);
5913                } catch (RemoteException e) {
5914                    /* ignore - same process */
5915                }
5916            }
5917        } finally {
5918            Binder.restoreCallingIdentity(identity);
5919        }
5920    }
5921
5922    /**
5923     * Compares two sets of signatures. Returns:
5924     * <br />
5925     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
5926     * <br />
5927     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
5928     * <br />
5929     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
5930     * <br />
5931     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
5932     * <br />
5933     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
5934     */
5935    static int compareSignatures(Signature[] s1, Signature[] s2) {
5936        if (s1 == null) {
5937            return s2 == null
5938                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
5939                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
5940        }
5941
5942        if (s2 == null) {
5943            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
5944        }
5945
5946        if (s1.length != s2.length) {
5947            return PackageManager.SIGNATURE_NO_MATCH;
5948        }
5949
5950        // Since both signature sets are of size 1, we can compare without HashSets.
5951        if (s1.length == 1) {
5952            return s1[0].equals(s2[0]) ?
5953                    PackageManager.SIGNATURE_MATCH :
5954                    PackageManager.SIGNATURE_NO_MATCH;
5955        }
5956
5957        ArraySet<Signature> set1 = new ArraySet<Signature>();
5958        for (Signature sig : s1) {
5959            set1.add(sig);
5960        }
5961        ArraySet<Signature> set2 = new ArraySet<Signature>();
5962        for (Signature sig : s2) {
5963            set2.add(sig);
5964        }
5965        // Make sure s2 contains all signatures in s1.
5966        if (set1.equals(set2)) {
5967            return PackageManager.SIGNATURE_MATCH;
5968        }
5969        return PackageManager.SIGNATURE_NO_MATCH;
5970    }
5971
5972    /**
5973     * If the database version for this type of package (internal storage or
5974     * external storage) is less than the version where package signatures
5975     * were updated, return true.
5976     */
5977    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5978        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5979        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5980    }
5981
5982    /**
5983     * Used for backward compatibility to make sure any packages with
5984     * certificate chains get upgraded to the new style. {@code existingSigs}
5985     * will be in the old format (since they were stored on disk from before the
5986     * system upgrade) and {@code scannedSigs} will be in the newer format.
5987     */
5988    private int compareSignaturesCompat(PackageSignatures existingSigs,
5989            PackageParser.Package scannedPkg) {
5990        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
5991            return PackageManager.SIGNATURE_NO_MATCH;
5992        }
5993
5994        ArraySet<Signature> existingSet = new ArraySet<Signature>();
5995        for (Signature sig : existingSigs.mSignatures) {
5996            existingSet.add(sig);
5997        }
5998        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
5999        for (Signature sig : scannedPkg.mSignatures) {
6000            try {
6001                Signature[] chainSignatures = sig.getChainSignatures();
6002                for (Signature chainSig : chainSignatures) {
6003                    scannedCompatSet.add(chainSig);
6004                }
6005            } catch (CertificateEncodingException e) {
6006                scannedCompatSet.add(sig);
6007            }
6008        }
6009        /*
6010         * Make sure the expanded scanned set contains all signatures in the
6011         * existing one.
6012         */
6013        if (scannedCompatSet.equals(existingSet)) {
6014            // Migrate the old signatures to the new scheme.
6015            existingSigs.assignSignatures(scannedPkg.mSignatures);
6016            // The new KeySets will be re-added later in the scanning process.
6017            synchronized (mPackages) {
6018                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
6019            }
6020            return PackageManager.SIGNATURE_MATCH;
6021        }
6022        return PackageManager.SIGNATURE_NO_MATCH;
6023    }
6024
6025    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6026        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6027        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
6028    }
6029
6030    private int compareSignaturesRecover(PackageSignatures existingSigs,
6031            PackageParser.Package scannedPkg) {
6032        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
6033            return PackageManager.SIGNATURE_NO_MATCH;
6034        }
6035
6036        String msg = null;
6037        try {
6038            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
6039                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
6040                        + scannedPkg.packageName);
6041                return PackageManager.SIGNATURE_MATCH;
6042            }
6043        } catch (CertificateException e) {
6044            msg = e.getMessage();
6045        }
6046
6047        logCriticalInfo(Log.INFO,
6048                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
6049        return PackageManager.SIGNATURE_NO_MATCH;
6050    }
6051
6052    @Override
6053    public List<String> getAllPackages() {
6054        final int callingUid = Binder.getCallingUid();
6055        final int callingUserId = UserHandle.getUserId(callingUid);
6056        synchronized (mPackages) {
6057            if (canViewInstantApps(callingUid, callingUserId)) {
6058                return new ArrayList<String>(mPackages.keySet());
6059            }
6060            final String instantAppPkgName = getInstantAppPackageName(callingUid);
6061            final List<String> result = new ArrayList<>();
6062            if (instantAppPkgName != null) {
6063                // caller is an instant application; filter unexposed applications
6064                for (PackageParser.Package pkg : mPackages.values()) {
6065                    if (!pkg.visibleToInstantApps) {
6066                        continue;
6067                    }
6068                    result.add(pkg.packageName);
6069                }
6070            } else {
6071                // caller is a normal application; filter instant applications
6072                for (PackageParser.Package pkg : mPackages.values()) {
6073                    final PackageSetting ps =
6074                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
6075                    if (ps != null
6076                            && ps.getInstantApp(callingUserId)
6077                            && !mInstantAppRegistry.isInstantAccessGranted(
6078                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
6079                        continue;
6080                    }
6081                    result.add(pkg.packageName);
6082                }
6083            }
6084            return result;
6085        }
6086    }
6087
6088    @Override
6089    public String[] getPackagesForUid(int uid) {
6090        final int callingUid = Binder.getCallingUid();
6091        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
6092        final int userId = UserHandle.getUserId(uid);
6093        uid = UserHandle.getAppId(uid);
6094        // reader
6095        synchronized (mPackages) {
6096            Object obj = mSettings.getUserIdLPr(uid);
6097            if (obj instanceof SharedUserSetting) {
6098                if (isCallerInstantApp) {
6099                    return null;
6100                }
6101                final SharedUserSetting sus = (SharedUserSetting) obj;
6102                final int N = sus.packages.size();
6103                String[] res = new String[N];
6104                final Iterator<PackageSetting> it = sus.packages.iterator();
6105                int i = 0;
6106                while (it.hasNext()) {
6107                    PackageSetting ps = it.next();
6108                    if (ps.getInstalled(userId)) {
6109                        res[i++] = ps.name;
6110                    } else {
6111                        res = ArrayUtils.removeElement(String.class, res, res[i]);
6112                    }
6113                }
6114                return res;
6115            } else if (obj instanceof PackageSetting) {
6116                final PackageSetting ps = (PackageSetting) obj;
6117                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
6118                    return new String[]{ps.name};
6119                }
6120            }
6121        }
6122        return null;
6123    }
6124
6125    @Override
6126    public String getNameForUid(int uid) {
6127        final int callingUid = Binder.getCallingUid();
6128        if (getInstantAppPackageName(callingUid) != null) {
6129            return null;
6130        }
6131        synchronized (mPackages) {
6132            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6133            if (obj instanceof SharedUserSetting) {
6134                final SharedUserSetting sus = (SharedUserSetting) obj;
6135                return sus.name + ":" + sus.userId;
6136            } else if (obj instanceof PackageSetting) {
6137                final PackageSetting ps = (PackageSetting) obj;
6138                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6139                    return null;
6140                }
6141                return ps.name;
6142            }
6143        }
6144        return null;
6145    }
6146
6147    @Override
6148    public int getUidForSharedUser(String sharedUserName) {
6149        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6150            return -1;
6151        }
6152        if (sharedUserName == null) {
6153            return -1;
6154        }
6155        // reader
6156        synchronized (mPackages) {
6157            SharedUserSetting suid;
6158            try {
6159                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
6160                if (suid != null) {
6161                    return suid.userId;
6162                }
6163            } catch (PackageManagerException ignore) {
6164                // can't happen, but, still need to catch it
6165            }
6166            return -1;
6167        }
6168    }
6169
6170    @Override
6171    public int getFlagsForUid(int uid) {
6172        final int callingUid = Binder.getCallingUid();
6173        if (getInstantAppPackageName(callingUid) != null) {
6174            return 0;
6175        }
6176        synchronized (mPackages) {
6177            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6178            if (obj instanceof SharedUserSetting) {
6179                final SharedUserSetting sus = (SharedUserSetting) obj;
6180                return sus.pkgFlags;
6181            } else if (obj instanceof PackageSetting) {
6182                final PackageSetting ps = (PackageSetting) obj;
6183                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6184                    return 0;
6185                }
6186                return ps.pkgFlags;
6187            }
6188        }
6189        return 0;
6190    }
6191
6192    @Override
6193    public int getPrivateFlagsForUid(int uid) {
6194        final int callingUid = Binder.getCallingUid();
6195        if (getInstantAppPackageName(callingUid) != null) {
6196            return 0;
6197        }
6198        synchronized (mPackages) {
6199            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6200            if (obj instanceof SharedUserSetting) {
6201                final SharedUserSetting sus = (SharedUserSetting) obj;
6202                return sus.pkgPrivateFlags;
6203            } else if (obj instanceof PackageSetting) {
6204                final PackageSetting ps = (PackageSetting) obj;
6205                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6206                    return 0;
6207                }
6208                return ps.pkgPrivateFlags;
6209            }
6210        }
6211        return 0;
6212    }
6213
6214    @Override
6215    public boolean isUidPrivileged(int uid) {
6216        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6217            return false;
6218        }
6219        uid = UserHandle.getAppId(uid);
6220        // reader
6221        synchronized (mPackages) {
6222            Object obj = mSettings.getUserIdLPr(uid);
6223            if (obj instanceof SharedUserSetting) {
6224                final SharedUserSetting sus = (SharedUserSetting) obj;
6225                final Iterator<PackageSetting> it = sus.packages.iterator();
6226                while (it.hasNext()) {
6227                    if (it.next().isPrivileged()) {
6228                        return true;
6229                    }
6230                }
6231            } else if (obj instanceof PackageSetting) {
6232                final PackageSetting ps = (PackageSetting) obj;
6233                return ps.isPrivileged();
6234            }
6235        }
6236        return false;
6237    }
6238
6239    @Override
6240    public String[] getAppOpPermissionPackages(String permissionName) {
6241        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6242            return null;
6243        }
6244        synchronized (mPackages) {
6245            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
6246            if (pkgs == null) {
6247                return null;
6248            }
6249            return pkgs.toArray(new String[pkgs.size()]);
6250        }
6251    }
6252
6253    @Override
6254    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
6255            int flags, int userId) {
6256        return resolveIntentInternal(
6257                intent, resolvedType, flags, userId, false /*includeInstantApps*/);
6258    }
6259
6260    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
6261            int flags, int userId, boolean resolveForStart) {
6262        try {
6263            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
6264
6265            if (!sUserManager.exists(userId)) return null;
6266            final int callingUid = Binder.getCallingUid();
6267            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
6268            enforceCrossUserPermission(callingUid, userId,
6269                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
6270
6271            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6272            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
6273                    flags, callingUid, userId, resolveForStart);
6274            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6275
6276            final ResolveInfo bestChoice =
6277                    chooseBestActivity(intent, resolvedType, flags, query, userId);
6278            return bestChoice;
6279        } finally {
6280            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6281        }
6282    }
6283
6284    @Override
6285    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
6286        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
6287            throw new SecurityException(
6288                    "findPersistentPreferredActivity can only be run by the system");
6289        }
6290        if (!sUserManager.exists(userId)) {
6291            return null;
6292        }
6293        final int callingUid = Binder.getCallingUid();
6294        intent = updateIntentForResolve(intent);
6295        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
6296        final int flags = updateFlagsForResolve(
6297                0, userId, intent, callingUid, false /*includeInstantApps*/);
6298        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6299                userId);
6300        synchronized (mPackages) {
6301            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
6302                    userId);
6303        }
6304    }
6305
6306    @Override
6307    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
6308            IntentFilter filter, int match, ComponentName activity) {
6309        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6310            return;
6311        }
6312        final int userId = UserHandle.getCallingUserId();
6313        if (DEBUG_PREFERRED) {
6314            Log.v(TAG, "setLastChosenActivity intent=" + intent
6315                + " resolvedType=" + resolvedType
6316                + " flags=" + flags
6317                + " filter=" + filter
6318                + " match=" + match
6319                + " activity=" + activity);
6320            filter.dump(new PrintStreamPrinter(System.out), "    ");
6321        }
6322        intent.setComponent(null);
6323        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6324                userId);
6325        // Find any earlier preferred or last chosen entries and nuke them
6326        findPreferredActivity(intent, resolvedType,
6327                flags, query, 0, false, true, false, userId);
6328        // Add the new activity as the last chosen for this filter
6329        addPreferredActivityInternal(filter, match, null, activity, false, userId,
6330                "Setting last chosen");
6331    }
6332
6333    @Override
6334    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
6335        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6336            return null;
6337        }
6338        final int userId = UserHandle.getCallingUserId();
6339        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
6340        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6341                userId);
6342        return findPreferredActivity(intent, resolvedType, flags, query, 0,
6343                false, false, false, userId);
6344    }
6345
6346    /**
6347     * Returns whether or not instant apps have been disabled remotely.
6348     */
6349    private boolean isEphemeralDisabled() {
6350        return mEphemeralAppsDisabled;
6351    }
6352
6353    private boolean isInstantAppAllowed(
6354            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
6355            boolean skipPackageCheck) {
6356        if (mInstantAppResolverConnection == null) {
6357            return false;
6358        }
6359        if (mInstantAppInstallerActivity == null) {
6360            return false;
6361        }
6362        if (intent.getComponent() != null) {
6363            return false;
6364        }
6365        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
6366            return false;
6367        }
6368        if (!skipPackageCheck && intent.getPackage() != null) {
6369            return false;
6370        }
6371        final boolean isWebUri = hasWebURI(intent);
6372        if (!isWebUri || intent.getData().getHost() == null) {
6373            return false;
6374        }
6375        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
6376        // Or if there's already an ephemeral app installed that handles the action
6377        synchronized (mPackages) {
6378            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
6379            for (int n = 0; n < count; n++) {
6380                final ResolveInfo info = resolvedActivities.get(n);
6381                final String packageName = info.activityInfo.packageName;
6382                final PackageSetting ps = mSettings.mPackages.get(packageName);
6383                if (ps != null) {
6384                    // only check domain verification status if the app is not a browser
6385                    if (!info.handleAllWebDataURI) {
6386                        // Try to get the status from User settings first
6387                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6388                        final int status = (int) (packedStatus >> 32);
6389                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
6390                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6391                            if (DEBUG_EPHEMERAL) {
6392                                Slog.v(TAG, "DENY instant app;"
6393                                    + " pkg: " + packageName + ", status: " + status);
6394                            }
6395                            return false;
6396                        }
6397                    }
6398                    if (ps.getInstantApp(userId)) {
6399                        if (DEBUG_EPHEMERAL) {
6400                            Slog.v(TAG, "DENY instant app installed;"
6401                                    + " pkg: " + packageName);
6402                        }
6403                        return false;
6404                    }
6405                }
6406            }
6407        }
6408        // We've exhausted all ways to deny ephemeral application; let the system look for them.
6409        return true;
6410    }
6411
6412    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
6413            Intent origIntent, String resolvedType, String callingPackage,
6414            Bundle verificationBundle, int userId) {
6415        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
6416                new InstantAppRequest(responseObj, origIntent, resolvedType,
6417                        callingPackage, userId, verificationBundle));
6418        mHandler.sendMessage(msg);
6419    }
6420
6421    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
6422            int flags, List<ResolveInfo> query, int userId) {
6423        if (query != null) {
6424            final int N = query.size();
6425            if (N == 1) {
6426                return query.get(0);
6427            } else if (N > 1) {
6428                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
6429                // If there is more than one activity with the same priority,
6430                // then let the user decide between them.
6431                ResolveInfo r0 = query.get(0);
6432                ResolveInfo r1 = query.get(1);
6433                if (DEBUG_INTENT_MATCHING || debug) {
6434                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
6435                            + r1.activityInfo.name + "=" + r1.priority);
6436                }
6437                // If the first activity has a higher priority, or a different
6438                // default, then it is always desirable to pick it.
6439                if (r0.priority != r1.priority
6440                        || r0.preferredOrder != r1.preferredOrder
6441                        || r0.isDefault != r1.isDefault) {
6442                    return query.get(0);
6443                }
6444                // If we have saved a preference for a preferred activity for
6445                // this Intent, use that.
6446                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
6447                        flags, query, r0.priority, true, false, debug, userId);
6448                if (ri != null) {
6449                    return ri;
6450                }
6451                // If we have an ephemeral app, use it
6452                for (int i = 0; i < N; i++) {
6453                    ri = query.get(i);
6454                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
6455                        final String packageName = ri.activityInfo.packageName;
6456                        final PackageSetting ps = mSettings.mPackages.get(packageName);
6457                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6458                        final int status = (int)(packedStatus >> 32);
6459                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6460                            return ri;
6461                        }
6462                    }
6463                }
6464                ri = new ResolveInfo(mResolveInfo);
6465                ri.activityInfo = new ActivityInfo(ri.activityInfo);
6466                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6467                // If all of the options come from the same package, show the application's
6468                // label and icon instead of the generic resolver's.
6469                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6470                // and then throw away the ResolveInfo itself, meaning that the caller loses
6471                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6472                // a fallback for this case; we only set the target package's resources on
6473                // the ResolveInfo, not the ActivityInfo.
6474                final String intentPackage = intent.getPackage();
6475                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6476                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6477                    ri.resolvePackageName = intentPackage;
6478                    if (userNeedsBadging(userId)) {
6479                        ri.noResourceId = true;
6480                    } else {
6481                        ri.icon = appi.icon;
6482                    }
6483                    ri.iconResourceId = appi.icon;
6484                    ri.labelRes = appi.labelRes;
6485                }
6486                ri.activityInfo.applicationInfo = new ApplicationInfo(
6487                        ri.activityInfo.applicationInfo);
6488                if (userId != 0) {
6489                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6490                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6491                }
6492                // Make sure that the resolver is displayable in car mode
6493                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6494                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6495                return ri;
6496            }
6497        }
6498        return null;
6499    }
6500
6501    /**
6502     * Return true if the given list is not empty and all of its contents have
6503     * an activityInfo with the given package name.
6504     */
6505    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6506        if (ArrayUtils.isEmpty(list)) {
6507            return false;
6508        }
6509        for (int i = 0, N = list.size(); i < N; i++) {
6510            final ResolveInfo ri = list.get(i);
6511            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6512            if (ai == null || !packageName.equals(ai.packageName)) {
6513                return false;
6514            }
6515        }
6516        return true;
6517    }
6518
6519    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6520            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6521        final int N = query.size();
6522        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6523                .get(userId);
6524        // Get the list of persistent preferred activities that handle the intent
6525        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6526        List<PersistentPreferredActivity> pprefs = ppir != null
6527                ? ppir.queryIntent(intent, resolvedType,
6528                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6529                        userId)
6530                : null;
6531        if (pprefs != null && pprefs.size() > 0) {
6532            final int M = pprefs.size();
6533            for (int i=0; i<M; i++) {
6534                final PersistentPreferredActivity ppa = pprefs.get(i);
6535                if (DEBUG_PREFERRED || debug) {
6536                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6537                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6538                            + "\n  component=" + ppa.mComponent);
6539                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6540                }
6541                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6542                        flags | MATCH_DISABLED_COMPONENTS, userId);
6543                if (DEBUG_PREFERRED || debug) {
6544                    Slog.v(TAG, "Found persistent preferred activity:");
6545                    if (ai != null) {
6546                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6547                    } else {
6548                        Slog.v(TAG, "  null");
6549                    }
6550                }
6551                if (ai == null) {
6552                    // This previously registered persistent preferred activity
6553                    // component is no longer known. Ignore it and do NOT remove it.
6554                    continue;
6555                }
6556                for (int j=0; j<N; j++) {
6557                    final ResolveInfo ri = query.get(j);
6558                    if (!ri.activityInfo.applicationInfo.packageName
6559                            .equals(ai.applicationInfo.packageName)) {
6560                        continue;
6561                    }
6562                    if (!ri.activityInfo.name.equals(ai.name)) {
6563                        continue;
6564                    }
6565                    //  Found a persistent preference that can handle the intent.
6566                    if (DEBUG_PREFERRED || debug) {
6567                        Slog.v(TAG, "Returning persistent preferred activity: " +
6568                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6569                    }
6570                    return ri;
6571                }
6572            }
6573        }
6574        return null;
6575    }
6576
6577    // TODO: handle preferred activities missing while user has amnesia
6578    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6579            List<ResolveInfo> query, int priority, boolean always,
6580            boolean removeMatches, boolean debug, int userId) {
6581        if (!sUserManager.exists(userId)) return null;
6582        final int callingUid = Binder.getCallingUid();
6583        flags = updateFlagsForResolve(
6584                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6585        intent = updateIntentForResolve(intent);
6586        // writer
6587        synchronized (mPackages) {
6588            // Try to find a matching persistent preferred activity.
6589            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6590                    debug, userId);
6591
6592            // If a persistent preferred activity matched, use it.
6593            if (pri != null) {
6594                return pri;
6595            }
6596
6597            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6598            // Get the list of preferred activities that handle the intent
6599            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6600            List<PreferredActivity> prefs = pir != null
6601                    ? pir.queryIntent(intent, resolvedType,
6602                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6603                            userId)
6604                    : null;
6605            if (prefs != null && prefs.size() > 0) {
6606                boolean changed = false;
6607                try {
6608                    // First figure out how good the original match set is.
6609                    // We will only allow preferred activities that came
6610                    // from the same match quality.
6611                    int match = 0;
6612
6613                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6614
6615                    final int N = query.size();
6616                    for (int j=0; j<N; j++) {
6617                        final ResolveInfo ri = query.get(j);
6618                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6619                                + ": 0x" + Integer.toHexString(match));
6620                        if (ri.match > match) {
6621                            match = ri.match;
6622                        }
6623                    }
6624
6625                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6626                            + Integer.toHexString(match));
6627
6628                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6629                    final int M = prefs.size();
6630                    for (int i=0; i<M; i++) {
6631                        final PreferredActivity pa = prefs.get(i);
6632                        if (DEBUG_PREFERRED || debug) {
6633                            Slog.v(TAG, "Checking PreferredActivity ds="
6634                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6635                                    + "\n  component=" + pa.mPref.mComponent);
6636                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6637                        }
6638                        if (pa.mPref.mMatch != match) {
6639                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6640                                    + Integer.toHexString(pa.mPref.mMatch));
6641                            continue;
6642                        }
6643                        // If it's not an "always" type preferred activity and that's what we're
6644                        // looking for, skip it.
6645                        if (always && !pa.mPref.mAlways) {
6646                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6647                            continue;
6648                        }
6649                        final ActivityInfo ai = getActivityInfo(
6650                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6651                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6652                                userId);
6653                        if (DEBUG_PREFERRED || debug) {
6654                            Slog.v(TAG, "Found preferred activity:");
6655                            if (ai != null) {
6656                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6657                            } else {
6658                                Slog.v(TAG, "  null");
6659                            }
6660                        }
6661                        if (ai == null) {
6662                            // This previously registered preferred activity
6663                            // component is no longer known.  Most likely an update
6664                            // to the app was installed and in the new version this
6665                            // component no longer exists.  Clean it up by removing
6666                            // it from the preferred activities list, and skip it.
6667                            Slog.w(TAG, "Removing dangling preferred activity: "
6668                                    + pa.mPref.mComponent);
6669                            pir.removeFilter(pa);
6670                            changed = true;
6671                            continue;
6672                        }
6673                        for (int j=0; j<N; j++) {
6674                            final ResolveInfo ri = query.get(j);
6675                            if (!ri.activityInfo.applicationInfo.packageName
6676                                    .equals(ai.applicationInfo.packageName)) {
6677                                continue;
6678                            }
6679                            if (!ri.activityInfo.name.equals(ai.name)) {
6680                                continue;
6681                            }
6682
6683                            if (removeMatches) {
6684                                pir.removeFilter(pa);
6685                                changed = true;
6686                                if (DEBUG_PREFERRED) {
6687                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6688                                }
6689                                break;
6690                            }
6691
6692                            // Okay we found a previously set preferred or last chosen app.
6693                            // If the result set is different from when this
6694                            // was created, we need to clear it and re-ask the
6695                            // user their preference, if we're looking for an "always" type entry.
6696                            if (always && !pa.mPref.sameSet(query)) {
6697                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
6698                                        + intent + " type " + resolvedType);
6699                                if (DEBUG_PREFERRED) {
6700                                    Slog.v(TAG, "Removing preferred activity since set changed "
6701                                            + pa.mPref.mComponent);
6702                                }
6703                                pir.removeFilter(pa);
6704                                // Re-add the filter as a "last chosen" entry (!always)
6705                                PreferredActivity lastChosen = new PreferredActivity(
6706                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6707                                pir.addFilter(lastChosen);
6708                                changed = true;
6709                                return null;
6710                            }
6711
6712                            // Yay! Either the set matched or we're looking for the last chosen
6713                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6714                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6715                            return ri;
6716                        }
6717                    }
6718                } finally {
6719                    if (changed) {
6720                        if (DEBUG_PREFERRED) {
6721                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6722                        }
6723                        scheduleWritePackageRestrictionsLocked(userId);
6724                    }
6725                }
6726            }
6727        }
6728        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6729        return null;
6730    }
6731
6732    /*
6733     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6734     */
6735    @Override
6736    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6737            int targetUserId) {
6738        mContext.enforceCallingOrSelfPermission(
6739                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6740        List<CrossProfileIntentFilter> matches =
6741                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6742        if (matches != null) {
6743            int size = matches.size();
6744            for (int i = 0; i < size; i++) {
6745                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6746            }
6747        }
6748        if (hasWebURI(intent)) {
6749            // cross-profile app linking works only towards the parent.
6750            final int callingUid = Binder.getCallingUid();
6751            final UserInfo parent = getProfileParent(sourceUserId);
6752            synchronized(mPackages) {
6753                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
6754                        false /*includeInstantApps*/);
6755                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6756                        intent, resolvedType, flags, sourceUserId, parent.id);
6757                return xpDomainInfo != null;
6758            }
6759        }
6760        return false;
6761    }
6762
6763    private UserInfo getProfileParent(int userId) {
6764        final long identity = Binder.clearCallingIdentity();
6765        try {
6766            return sUserManager.getProfileParent(userId);
6767        } finally {
6768            Binder.restoreCallingIdentity(identity);
6769        }
6770    }
6771
6772    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6773            String resolvedType, int userId) {
6774        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6775        if (resolver != null) {
6776            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6777        }
6778        return null;
6779    }
6780
6781    @Override
6782    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6783            String resolvedType, int flags, int userId) {
6784        try {
6785            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6786
6787            return new ParceledListSlice<>(
6788                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6789        } finally {
6790            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6791        }
6792    }
6793
6794    /**
6795     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6796     * instant, returns {@code null}.
6797     */
6798    private String getInstantAppPackageName(int callingUid) {
6799        synchronized (mPackages) {
6800            // If the caller is an isolated app use the owner's uid for the lookup.
6801            if (Process.isIsolated(callingUid)) {
6802                callingUid = mIsolatedOwners.get(callingUid);
6803            }
6804            final int appId = UserHandle.getAppId(callingUid);
6805            final Object obj = mSettings.getUserIdLPr(appId);
6806            if (obj instanceof PackageSetting) {
6807                final PackageSetting ps = (PackageSetting) obj;
6808                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6809                return isInstantApp ? ps.pkg.packageName : null;
6810            }
6811        }
6812        return null;
6813    }
6814
6815    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6816            String resolvedType, int flags, int userId) {
6817        return queryIntentActivitiesInternal(
6818                intent, resolvedType, flags, Binder.getCallingUid(), userId, false);
6819    }
6820
6821    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6822            String resolvedType, int flags, int filterCallingUid, int userId,
6823            boolean resolveForStart) {
6824        if (!sUserManager.exists(userId)) return Collections.emptyList();
6825        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
6826        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6827                false /* requireFullPermission */, false /* checkShell */,
6828                "query intent activities");
6829        final String pkgName = intent.getPackage();
6830        ComponentName comp = intent.getComponent();
6831        if (comp == null) {
6832            if (intent.getSelector() != null) {
6833                intent = intent.getSelector();
6834                comp = intent.getComponent();
6835            }
6836        }
6837
6838        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
6839                comp != null || pkgName != null /*onlyExposedExplicitly*/);
6840        if (comp != null) {
6841            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6842            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6843            if (ai != null) {
6844                // When specifying an explicit component, we prevent the activity from being
6845                // used when either 1) the calling package is normal and the activity is within
6846                // an ephemeral application or 2) the calling package is ephemeral and the
6847                // activity is not visible to ephemeral applications.
6848                final boolean matchInstantApp =
6849                        (flags & PackageManager.MATCH_INSTANT) != 0;
6850                final boolean matchVisibleToInstantAppOnly =
6851                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6852                final boolean matchExplicitlyVisibleOnly =
6853                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
6854                final boolean isCallerInstantApp =
6855                        instantAppPkgName != null;
6856                final boolean isTargetSameInstantApp =
6857                        comp.getPackageName().equals(instantAppPkgName);
6858                final boolean isTargetInstantApp =
6859                        (ai.applicationInfo.privateFlags
6860                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6861                final boolean isTargetVisibleToInstantApp =
6862                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
6863                final boolean isTargetExplicitlyVisibleToInstantApp =
6864                        isTargetVisibleToInstantApp
6865                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
6866                final boolean isTargetHiddenFromInstantApp =
6867                        !isTargetVisibleToInstantApp
6868                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
6869                final boolean blockResolution =
6870                        !isTargetSameInstantApp
6871                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6872                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6873                                        && isTargetHiddenFromInstantApp));
6874                if (!blockResolution) {
6875                    final ResolveInfo ri = new ResolveInfo();
6876                    ri.activityInfo = ai;
6877                    list.add(ri);
6878                }
6879            }
6880            return applyPostResolutionFilter(list, instantAppPkgName);
6881        }
6882
6883        // reader
6884        boolean sortResult = false;
6885        boolean addEphemeral = false;
6886        List<ResolveInfo> result;
6887        final boolean ephemeralDisabled = isEphemeralDisabled();
6888        synchronized (mPackages) {
6889            if (pkgName == null) {
6890                List<CrossProfileIntentFilter> matchingFilters =
6891                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6892                // Check for results that need to skip the current profile.
6893                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6894                        resolvedType, flags, userId);
6895                if (xpResolveInfo != null) {
6896                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6897                    xpResult.add(xpResolveInfo);
6898                    return applyPostResolutionFilter(
6899                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName);
6900                }
6901
6902                // Check for results in the current profile.
6903                result = filterIfNotSystemUser(mActivities.queryIntent(
6904                        intent, resolvedType, flags, userId), userId);
6905                addEphemeral = !ephemeralDisabled
6906                        && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/);
6907                // Check for cross profile results.
6908                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6909                xpResolveInfo = queryCrossProfileIntents(
6910                        matchingFilters, intent, resolvedType, flags, userId,
6911                        hasNonNegativePriorityResult);
6912                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6913                    boolean isVisibleToUser = filterIfNotSystemUser(
6914                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6915                    if (isVisibleToUser) {
6916                        result.add(xpResolveInfo);
6917                        sortResult = true;
6918                    }
6919                }
6920                if (hasWebURI(intent)) {
6921                    CrossProfileDomainInfo xpDomainInfo = null;
6922                    final UserInfo parent = getProfileParent(userId);
6923                    if (parent != null) {
6924                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6925                                flags, userId, parent.id);
6926                    }
6927                    if (xpDomainInfo != null) {
6928                        if (xpResolveInfo != null) {
6929                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6930                            // in the result.
6931                            result.remove(xpResolveInfo);
6932                        }
6933                        if (result.size() == 0 && !addEphemeral) {
6934                            // No result in current profile, but found candidate in parent user.
6935                            // And we are not going to add emphemeral app, so we can return the
6936                            // result straight away.
6937                            result.add(xpDomainInfo.resolveInfo);
6938                            return applyPostResolutionFilter(result, instantAppPkgName);
6939                        }
6940                    } else if (result.size() <= 1 && !addEphemeral) {
6941                        // No result in parent user and <= 1 result in current profile, and we
6942                        // are not going to add emphemeral app, so we can return the result without
6943                        // further processing.
6944                        return applyPostResolutionFilter(result, instantAppPkgName);
6945                    }
6946                    // We have more than one candidate (combining results from current and parent
6947                    // profile), so we need filtering and sorting.
6948                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6949                            intent, flags, result, xpDomainInfo, userId);
6950                    sortResult = true;
6951                }
6952            } else {
6953                final PackageParser.Package pkg = mPackages.get(pkgName);
6954                result = null;
6955                if (pkg != null) {
6956                    result = filterIfNotSystemUser(
6957                            mActivities.queryIntentForPackage(
6958                                    intent, resolvedType, flags, pkg.activities, userId),
6959                            userId);
6960                }
6961                if (result == null || result.size() == 0) {
6962                    // the caller wants to resolve for a particular package; however, there
6963                    // were no installed results, so, try to find an ephemeral result
6964                    addEphemeral = !ephemeralDisabled
6965                            && isInstantAppAllowed(
6966                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
6967                    if (result == null) {
6968                        result = new ArrayList<>();
6969                    }
6970                }
6971            }
6972        }
6973        if (addEphemeral) {
6974            result = maybeAddInstantAppInstaller(result, intent, resolvedType, flags, userId);
6975        }
6976        if (sortResult) {
6977            Collections.sort(result, mResolvePrioritySorter);
6978        }
6979        return applyPostResolutionFilter(result, instantAppPkgName);
6980    }
6981
6982    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
6983            String resolvedType, int flags, int userId) {
6984        // first, check to see if we've got an instant app already installed
6985        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
6986        ResolveInfo localInstantApp = null;
6987        boolean blockResolution = false;
6988        if (!alreadyResolvedLocally) {
6989            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
6990                    flags
6991                        | PackageManager.GET_RESOLVED_FILTER
6992                        | PackageManager.MATCH_INSTANT
6993                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
6994                    userId);
6995            for (int i = instantApps.size() - 1; i >= 0; --i) {
6996                final ResolveInfo info = instantApps.get(i);
6997                final String packageName = info.activityInfo.packageName;
6998                final PackageSetting ps = mSettings.mPackages.get(packageName);
6999                if (ps.getInstantApp(userId)) {
7000                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7001                    final int status = (int)(packedStatus >> 32);
7002                    final int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7003                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7004                        // there's a local instant application installed, but, the user has
7005                        // chosen to never use it; skip resolution and don't acknowledge
7006                        // an instant application is even available
7007                        if (DEBUG_EPHEMERAL) {
7008                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
7009                        }
7010                        blockResolution = true;
7011                        break;
7012                    } else {
7013                        // we have a locally installed instant application; skip resolution
7014                        // but acknowledge there's an instant application available
7015                        if (DEBUG_EPHEMERAL) {
7016                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
7017                        }
7018                        localInstantApp = info;
7019                        break;
7020                    }
7021                }
7022            }
7023        }
7024        // no app installed, let's see if one's available
7025        AuxiliaryResolveInfo auxiliaryResponse = null;
7026        if (!blockResolution) {
7027            if (localInstantApp == null) {
7028                // we don't have an instant app locally, resolve externally
7029                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
7030                final InstantAppRequest requestObject = new InstantAppRequest(
7031                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
7032                        null /*callingPackage*/, userId, null /*verificationBundle*/);
7033                auxiliaryResponse =
7034                        InstantAppResolver.doInstantAppResolutionPhaseOne(
7035                                mContext, mInstantAppResolverConnection, requestObject);
7036                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7037            } else {
7038                // we have an instant application locally, but, we can't admit that since
7039                // callers shouldn't be able to determine prior browsing. create a dummy
7040                // auxiliary response so the downstream code behaves as if there's an
7041                // instant application available externally. when it comes time to start
7042                // the instant application, we'll do the right thing.
7043                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
7044                auxiliaryResponse = new AuxiliaryResolveInfo(
7045                        ai.packageName, null /*splitName*/, ai.versionCode, null /*failureIntent*/);
7046            }
7047        }
7048        if (auxiliaryResponse != null) {
7049            if (DEBUG_EPHEMERAL) {
7050                Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7051            }
7052            final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
7053            final PackageSetting ps =
7054                    mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
7055            if (ps != null) {
7056                ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
7057                        mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
7058                ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
7059                ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
7060                // make sure this resolver is the default
7061                ephemeralInstaller.isDefault = true;
7062                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7063                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7064                // add a non-generic filter
7065                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
7066                ephemeralInstaller.filter.addDataPath(
7067                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
7068                ephemeralInstaller.isInstantAppAvailable = true;
7069                result.add(ephemeralInstaller);
7070            }
7071        }
7072        return result;
7073    }
7074
7075    private static class CrossProfileDomainInfo {
7076        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
7077        ResolveInfo resolveInfo;
7078        /* Best domain verification status of the activities found in the other profile */
7079        int bestDomainVerificationStatus;
7080    }
7081
7082    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
7083            String resolvedType, int flags, int sourceUserId, int parentUserId) {
7084        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
7085                sourceUserId)) {
7086            return null;
7087        }
7088        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7089                resolvedType, flags, parentUserId);
7090
7091        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
7092            return null;
7093        }
7094        CrossProfileDomainInfo result = null;
7095        int size = resultTargetUser.size();
7096        for (int i = 0; i < size; i++) {
7097            ResolveInfo riTargetUser = resultTargetUser.get(i);
7098            // Intent filter verification is only for filters that specify a host. So don't return
7099            // those that handle all web uris.
7100            if (riTargetUser.handleAllWebDataURI) {
7101                continue;
7102            }
7103            String packageName = riTargetUser.activityInfo.packageName;
7104            PackageSetting ps = mSettings.mPackages.get(packageName);
7105            if (ps == null) {
7106                continue;
7107            }
7108            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
7109            int status = (int)(verificationState >> 32);
7110            if (result == null) {
7111                result = new CrossProfileDomainInfo();
7112                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
7113                        sourceUserId, parentUserId);
7114                result.bestDomainVerificationStatus = status;
7115            } else {
7116                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
7117                        result.bestDomainVerificationStatus);
7118            }
7119        }
7120        // Don't consider matches with status NEVER across profiles.
7121        if (result != null && result.bestDomainVerificationStatus
7122                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7123            return null;
7124        }
7125        return result;
7126    }
7127
7128    /**
7129     * Verification statuses are ordered from the worse to the best, except for
7130     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
7131     */
7132    private int bestDomainVerificationStatus(int status1, int status2) {
7133        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7134            return status2;
7135        }
7136        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7137            return status1;
7138        }
7139        return (int) MathUtils.max(status1, status2);
7140    }
7141
7142    private boolean isUserEnabled(int userId) {
7143        long callingId = Binder.clearCallingIdentity();
7144        try {
7145            UserInfo userInfo = sUserManager.getUserInfo(userId);
7146            return userInfo != null && userInfo.isEnabled();
7147        } finally {
7148            Binder.restoreCallingIdentity(callingId);
7149        }
7150    }
7151
7152    /**
7153     * Filter out activities with systemUserOnly flag set, when current user is not System.
7154     *
7155     * @return filtered list
7156     */
7157    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
7158        if (userId == UserHandle.USER_SYSTEM) {
7159            return resolveInfos;
7160        }
7161        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7162            ResolveInfo info = resolveInfos.get(i);
7163            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
7164                resolveInfos.remove(i);
7165            }
7166        }
7167        return resolveInfos;
7168    }
7169
7170    /**
7171     * Filters out ephemeral activities.
7172     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
7173     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
7174     *
7175     * @param resolveInfos The pre-filtered list of resolved activities
7176     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
7177     *          is performed.
7178     * @return A filtered list of resolved activities.
7179     */
7180    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
7181            String ephemeralPkgName) {
7182        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7183            final ResolveInfo info = resolveInfos.get(i);
7184            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
7185            // TODO: When adding on-demand split support for non-instant apps, remove this check
7186            // and always apply post filtering
7187            // allow activities that are defined in the provided package
7188            if (isEphemeralApp) {
7189                if (info.activityInfo.splitName != null
7190                        && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
7191                                info.activityInfo.splitName)) {
7192                    // requested activity is defined in a split that hasn't been installed yet.
7193                    // add the installer to the resolve list
7194                    if (DEBUG_EPHEMERAL) {
7195                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7196                    }
7197                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7198                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7199                            info.activityInfo.packageName, info.activityInfo.splitName,
7200                            info.activityInfo.applicationInfo.versionCode, null /*failureIntent*/);
7201                    // make sure this resolver is the default
7202                    installerInfo.isDefault = true;
7203                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7204                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7205                    // add a non-generic filter
7206                    installerInfo.filter = new IntentFilter();
7207                    // load resources from the correct package
7208                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7209                    resolveInfos.set(i, installerInfo);
7210                    continue;
7211                }
7212            }
7213            // caller is a full app, don't need to apply any other filtering
7214            if (ephemeralPkgName == null) {
7215                continue;
7216            } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
7217                // caller is same app; don't need to apply any other filtering
7218                continue;
7219            }
7220            // allow activities that have been explicitly exposed to ephemeral apps
7221            if (!isEphemeralApp
7222                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7223                continue;
7224            }
7225            resolveInfos.remove(i);
7226        }
7227        return resolveInfos;
7228    }
7229
7230    /**
7231     * @param resolveInfos list of resolve infos in descending priority order
7232     * @return if the list contains a resolve info with non-negative priority
7233     */
7234    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
7235        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
7236    }
7237
7238    private static boolean hasWebURI(Intent intent) {
7239        if (intent.getData() == null) {
7240            return false;
7241        }
7242        final String scheme = intent.getScheme();
7243        if (TextUtils.isEmpty(scheme)) {
7244            return false;
7245        }
7246        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
7247    }
7248
7249    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
7250            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
7251            int userId) {
7252        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
7253
7254        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7255            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
7256                    candidates.size());
7257        }
7258
7259        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
7260        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
7261        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
7262        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
7263        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
7264        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
7265
7266        synchronized (mPackages) {
7267            final int count = candidates.size();
7268            // First, try to use linked apps. Partition the candidates into four lists:
7269            // one for the final results, one for the "do not use ever", one for "undefined status"
7270            // and finally one for "browser app type".
7271            for (int n=0; n<count; n++) {
7272                ResolveInfo info = candidates.get(n);
7273                String packageName = info.activityInfo.packageName;
7274                PackageSetting ps = mSettings.mPackages.get(packageName);
7275                if (ps != null) {
7276                    // Add to the special match all list (Browser use case)
7277                    if (info.handleAllWebDataURI) {
7278                        matchAllList.add(info);
7279                        continue;
7280                    }
7281                    // Try to get the status from User settings first
7282                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7283                    int status = (int)(packedStatus >> 32);
7284                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7285                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
7286                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7287                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
7288                                    + " : linkgen=" + linkGeneration);
7289                        }
7290                        // Use link-enabled generation as preferredOrder, i.e.
7291                        // prefer newly-enabled over earlier-enabled.
7292                        info.preferredOrder = linkGeneration;
7293                        alwaysList.add(info);
7294                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7295                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7296                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
7297                        }
7298                        neverList.add(info);
7299                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
7300                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7301                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
7302                        }
7303                        alwaysAskList.add(info);
7304                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
7305                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
7306                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7307                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
7308                        }
7309                        undefinedList.add(info);
7310                    }
7311                }
7312            }
7313
7314            // We'll want to include browser possibilities in a few cases
7315            boolean includeBrowser = false;
7316
7317            // First try to add the "always" resolution(s) for the current user, if any
7318            if (alwaysList.size() > 0) {
7319                result.addAll(alwaysList);
7320            } else {
7321                // Add all undefined apps as we want them to appear in the disambiguation dialog.
7322                result.addAll(undefinedList);
7323                // Maybe add one for the other profile.
7324                if (xpDomainInfo != null && (
7325                        xpDomainInfo.bestDomainVerificationStatus
7326                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
7327                    result.add(xpDomainInfo.resolveInfo);
7328                }
7329                includeBrowser = true;
7330            }
7331
7332            // The presence of any 'always ask' alternatives means we'll also offer browsers.
7333            // If there were 'always' entries their preferred order has been set, so we also
7334            // back that off to make the alternatives equivalent
7335            if (alwaysAskList.size() > 0) {
7336                for (ResolveInfo i : result) {
7337                    i.preferredOrder = 0;
7338                }
7339                result.addAll(alwaysAskList);
7340                includeBrowser = true;
7341            }
7342
7343            if (includeBrowser) {
7344                // Also add browsers (all of them or only the default one)
7345                if (DEBUG_DOMAIN_VERIFICATION) {
7346                    Slog.v(TAG, "   ...including browsers in candidate set");
7347                }
7348                if ((matchFlags & MATCH_ALL) != 0) {
7349                    result.addAll(matchAllList);
7350                } else {
7351                    // Browser/generic handling case.  If there's a default browser, go straight
7352                    // to that (but only if there is no other higher-priority match).
7353                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7354                    int maxMatchPrio = 0;
7355                    ResolveInfo defaultBrowserMatch = null;
7356                    final int numCandidates = matchAllList.size();
7357                    for (int n = 0; n < numCandidates; n++) {
7358                        ResolveInfo info = matchAllList.get(n);
7359                        // track the highest overall match priority...
7360                        if (info.priority > maxMatchPrio) {
7361                            maxMatchPrio = info.priority;
7362                        }
7363                        // ...and the highest-priority default browser match
7364                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7365                            if (defaultBrowserMatch == null
7366                                    || (defaultBrowserMatch.priority < info.priority)) {
7367                                if (debug) {
7368                                    Slog.v(TAG, "Considering default browser match " + info);
7369                                }
7370                                defaultBrowserMatch = info;
7371                            }
7372                        }
7373                    }
7374                    if (defaultBrowserMatch != null
7375                            && defaultBrowserMatch.priority >= maxMatchPrio
7376                            && !TextUtils.isEmpty(defaultBrowserPackageName))
7377                    {
7378                        if (debug) {
7379                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7380                        }
7381                        result.add(defaultBrowserMatch);
7382                    } else {
7383                        result.addAll(matchAllList);
7384                    }
7385                }
7386
7387                // If there is nothing selected, add all candidates and remove the ones that the user
7388                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7389                if (result.size() == 0) {
7390                    result.addAll(candidates);
7391                    result.removeAll(neverList);
7392                }
7393            }
7394        }
7395        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7396            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7397                    result.size());
7398            for (ResolveInfo info : result) {
7399                Slog.v(TAG, "  + " + info.activityInfo);
7400            }
7401        }
7402        return result;
7403    }
7404
7405    // Returns a packed value as a long:
7406    //
7407    // high 'int'-sized word: link status: undefined/ask/never/always.
7408    // low 'int'-sized word: relative priority among 'always' results.
7409    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7410        long result = ps.getDomainVerificationStatusForUser(userId);
7411        // if none available, get the master status
7412        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7413            if (ps.getIntentFilterVerificationInfo() != null) {
7414                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7415            }
7416        }
7417        return result;
7418    }
7419
7420    private ResolveInfo querySkipCurrentProfileIntents(
7421            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7422            int flags, int sourceUserId) {
7423        if (matchingFilters != null) {
7424            int size = matchingFilters.size();
7425            for (int i = 0; i < size; i ++) {
7426                CrossProfileIntentFilter filter = matchingFilters.get(i);
7427                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7428                    // Checking if there are activities in the target user that can handle the
7429                    // intent.
7430                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7431                            resolvedType, flags, sourceUserId);
7432                    if (resolveInfo != null) {
7433                        return resolveInfo;
7434                    }
7435                }
7436            }
7437        }
7438        return null;
7439    }
7440
7441    // Return matching ResolveInfo in target user if any.
7442    private ResolveInfo queryCrossProfileIntents(
7443            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7444            int flags, int sourceUserId, boolean matchInCurrentProfile) {
7445        if (matchingFilters != null) {
7446            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7447            // match the same intent. For performance reasons, it is better not to
7448            // run queryIntent twice for the same userId
7449            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7450            int size = matchingFilters.size();
7451            for (int i = 0; i < size; i++) {
7452                CrossProfileIntentFilter filter = matchingFilters.get(i);
7453                int targetUserId = filter.getTargetUserId();
7454                boolean skipCurrentProfile =
7455                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7456                boolean skipCurrentProfileIfNoMatchFound =
7457                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7458                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7459                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7460                    // Checking if there are activities in the target user that can handle the
7461                    // intent.
7462                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7463                            resolvedType, flags, sourceUserId);
7464                    if (resolveInfo != null) return resolveInfo;
7465                    alreadyTriedUserIds.put(targetUserId, true);
7466                }
7467            }
7468        }
7469        return null;
7470    }
7471
7472    /**
7473     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7474     * will forward the intent to the filter's target user.
7475     * Otherwise, returns null.
7476     */
7477    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7478            String resolvedType, int flags, int sourceUserId) {
7479        int targetUserId = filter.getTargetUserId();
7480        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7481                resolvedType, flags, targetUserId);
7482        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7483            // If all the matches in the target profile are suspended, return null.
7484            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7485                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7486                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7487                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7488                            targetUserId);
7489                }
7490            }
7491        }
7492        return null;
7493    }
7494
7495    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7496            int sourceUserId, int targetUserId) {
7497        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7498        long ident = Binder.clearCallingIdentity();
7499        boolean targetIsProfile;
7500        try {
7501            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7502        } finally {
7503            Binder.restoreCallingIdentity(ident);
7504        }
7505        String className;
7506        if (targetIsProfile) {
7507            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7508        } else {
7509            className = FORWARD_INTENT_TO_PARENT;
7510        }
7511        ComponentName forwardingActivityComponentName = new ComponentName(
7512                mAndroidApplication.packageName, className);
7513        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7514                sourceUserId);
7515        if (!targetIsProfile) {
7516            forwardingActivityInfo.showUserIcon = targetUserId;
7517            forwardingResolveInfo.noResourceId = true;
7518        }
7519        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7520        forwardingResolveInfo.priority = 0;
7521        forwardingResolveInfo.preferredOrder = 0;
7522        forwardingResolveInfo.match = 0;
7523        forwardingResolveInfo.isDefault = true;
7524        forwardingResolveInfo.filter = filter;
7525        forwardingResolveInfo.targetUserId = targetUserId;
7526        return forwardingResolveInfo;
7527    }
7528
7529    @Override
7530    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7531            Intent[] specifics, String[] specificTypes, Intent intent,
7532            String resolvedType, int flags, int userId) {
7533        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7534                specificTypes, intent, resolvedType, flags, userId));
7535    }
7536
7537    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7538            Intent[] specifics, String[] specificTypes, Intent intent,
7539            String resolvedType, int flags, int userId) {
7540        if (!sUserManager.exists(userId)) return Collections.emptyList();
7541        final int callingUid = Binder.getCallingUid();
7542        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7543                false /*includeInstantApps*/);
7544        enforceCrossUserPermission(callingUid, userId,
7545                false /*requireFullPermission*/, false /*checkShell*/,
7546                "query intent activity options");
7547        final String resultsAction = intent.getAction();
7548
7549        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7550                | PackageManager.GET_RESOLVED_FILTER, userId);
7551
7552        if (DEBUG_INTENT_MATCHING) {
7553            Log.v(TAG, "Query " + intent + ": " + results);
7554        }
7555
7556        int specificsPos = 0;
7557        int N;
7558
7559        // todo: note that the algorithm used here is O(N^2).  This
7560        // isn't a problem in our current environment, but if we start running
7561        // into situations where we have more than 5 or 10 matches then this
7562        // should probably be changed to something smarter...
7563
7564        // First we go through and resolve each of the specific items
7565        // that were supplied, taking care of removing any corresponding
7566        // duplicate items in the generic resolve list.
7567        if (specifics != null) {
7568            for (int i=0; i<specifics.length; i++) {
7569                final Intent sintent = specifics[i];
7570                if (sintent == null) {
7571                    continue;
7572                }
7573
7574                if (DEBUG_INTENT_MATCHING) {
7575                    Log.v(TAG, "Specific #" + i + ": " + sintent);
7576                }
7577
7578                String action = sintent.getAction();
7579                if (resultsAction != null && resultsAction.equals(action)) {
7580                    // If this action was explicitly requested, then don't
7581                    // remove things that have it.
7582                    action = null;
7583                }
7584
7585                ResolveInfo ri = null;
7586                ActivityInfo ai = null;
7587
7588                ComponentName comp = sintent.getComponent();
7589                if (comp == null) {
7590                    ri = resolveIntent(
7591                        sintent,
7592                        specificTypes != null ? specificTypes[i] : null,
7593                            flags, userId);
7594                    if (ri == null) {
7595                        continue;
7596                    }
7597                    if (ri == mResolveInfo) {
7598                        // ACK!  Must do something better with this.
7599                    }
7600                    ai = ri.activityInfo;
7601                    comp = new ComponentName(ai.applicationInfo.packageName,
7602                            ai.name);
7603                } else {
7604                    ai = getActivityInfo(comp, flags, userId);
7605                    if (ai == null) {
7606                        continue;
7607                    }
7608                }
7609
7610                // Look for any generic query activities that are duplicates
7611                // of this specific one, and remove them from the results.
7612                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
7613                N = results.size();
7614                int j;
7615                for (j=specificsPos; j<N; j++) {
7616                    ResolveInfo sri = results.get(j);
7617                    if ((sri.activityInfo.name.equals(comp.getClassName())
7618                            && sri.activityInfo.applicationInfo.packageName.equals(
7619                                    comp.getPackageName()))
7620                        || (action != null && sri.filter.matchAction(action))) {
7621                        results.remove(j);
7622                        if (DEBUG_INTENT_MATCHING) Log.v(
7623                            TAG, "Removing duplicate item from " + j
7624                            + " due to specific " + specificsPos);
7625                        if (ri == null) {
7626                            ri = sri;
7627                        }
7628                        j--;
7629                        N--;
7630                    }
7631                }
7632
7633                // Add this specific item to its proper place.
7634                if (ri == null) {
7635                    ri = new ResolveInfo();
7636                    ri.activityInfo = ai;
7637                }
7638                results.add(specificsPos, ri);
7639                ri.specificIndex = i;
7640                specificsPos++;
7641            }
7642        }
7643
7644        // Now we go through the remaining generic results and remove any
7645        // duplicate actions that are found here.
7646        N = results.size();
7647        for (int i=specificsPos; i<N-1; i++) {
7648            final ResolveInfo rii = results.get(i);
7649            if (rii.filter == null) {
7650                continue;
7651            }
7652
7653            // Iterate over all of the actions of this result's intent
7654            // filter...  typically this should be just one.
7655            final Iterator<String> it = rii.filter.actionsIterator();
7656            if (it == null) {
7657                continue;
7658            }
7659            while (it.hasNext()) {
7660                final String action = it.next();
7661                if (resultsAction != null && resultsAction.equals(action)) {
7662                    // If this action was explicitly requested, then don't
7663                    // remove things that have it.
7664                    continue;
7665                }
7666                for (int j=i+1; j<N; j++) {
7667                    final ResolveInfo rij = results.get(j);
7668                    if (rij.filter != null && rij.filter.hasAction(action)) {
7669                        results.remove(j);
7670                        if (DEBUG_INTENT_MATCHING) Log.v(
7671                            TAG, "Removing duplicate item from " + j
7672                            + " due to action " + action + " at " + i);
7673                        j--;
7674                        N--;
7675                    }
7676                }
7677            }
7678
7679            // If the caller didn't request filter information, drop it now
7680            // so we don't have to marshall/unmarshall it.
7681            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7682                rii.filter = null;
7683            }
7684        }
7685
7686        // Filter out the caller activity if so requested.
7687        if (caller != null) {
7688            N = results.size();
7689            for (int i=0; i<N; i++) {
7690                ActivityInfo ainfo = results.get(i).activityInfo;
7691                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
7692                        && caller.getClassName().equals(ainfo.name)) {
7693                    results.remove(i);
7694                    break;
7695                }
7696            }
7697        }
7698
7699        // If the caller didn't request filter information,
7700        // drop them now so we don't have to
7701        // marshall/unmarshall it.
7702        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7703            N = results.size();
7704            for (int i=0; i<N; i++) {
7705                results.get(i).filter = null;
7706            }
7707        }
7708
7709        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
7710        return results;
7711    }
7712
7713    @Override
7714    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
7715            String resolvedType, int flags, int userId) {
7716        return new ParceledListSlice<>(
7717                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
7718    }
7719
7720    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
7721            String resolvedType, int flags, int userId) {
7722        if (!sUserManager.exists(userId)) return Collections.emptyList();
7723        final int callingUid = Binder.getCallingUid();
7724        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7725        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7726                false /*includeInstantApps*/);
7727        ComponentName comp = intent.getComponent();
7728        if (comp == null) {
7729            if (intent.getSelector() != null) {
7730                intent = intent.getSelector();
7731                comp = intent.getComponent();
7732            }
7733        }
7734        if (comp != null) {
7735            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7736            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
7737            if (ai != null) {
7738                // When specifying an explicit component, we prevent the activity from being
7739                // used when either 1) the calling package is normal and the activity is within
7740                // an instant application or 2) the calling package is ephemeral and the
7741                // activity is not visible to instant applications.
7742                final boolean matchInstantApp =
7743                        (flags & PackageManager.MATCH_INSTANT) != 0;
7744                final boolean matchVisibleToInstantAppOnly =
7745                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7746                final boolean matchExplicitlyVisibleOnly =
7747                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7748                final boolean isCallerInstantApp =
7749                        instantAppPkgName != null;
7750                final boolean isTargetSameInstantApp =
7751                        comp.getPackageName().equals(instantAppPkgName);
7752                final boolean isTargetInstantApp =
7753                        (ai.applicationInfo.privateFlags
7754                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7755                final boolean isTargetVisibleToInstantApp =
7756                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7757                final boolean isTargetExplicitlyVisibleToInstantApp =
7758                        isTargetVisibleToInstantApp
7759                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7760                final boolean isTargetHiddenFromInstantApp =
7761                        !isTargetVisibleToInstantApp
7762                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7763                final boolean blockResolution =
7764                        !isTargetSameInstantApp
7765                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7766                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7767                                        && isTargetHiddenFromInstantApp));
7768                if (!blockResolution) {
7769                    ResolveInfo ri = new ResolveInfo();
7770                    ri.activityInfo = ai;
7771                    list.add(ri);
7772                }
7773            }
7774            return applyPostResolutionFilter(list, instantAppPkgName);
7775        }
7776
7777        // reader
7778        synchronized (mPackages) {
7779            String pkgName = intent.getPackage();
7780            if (pkgName == null) {
7781                final List<ResolveInfo> result =
7782                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
7783                return applyPostResolutionFilter(result, instantAppPkgName);
7784            }
7785            final PackageParser.Package pkg = mPackages.get(pkgName);
7786            if (pkg != null) {
7787                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
7788                        intent, resolvedType, flags, pkg.receivers, userId);
7789                return applyPostResolutionFilter(result, instantAppPkgName);
7790            }
7791            return Collections.emptyList();
7792        }
7793    }
7794
7795    @Override
7796    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7797        final int callingUid = Binder.getCallingUid();
7798        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
7799    }
7800
7801    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
7802            int userId, int callingUid) {
7803        if (!sUserManager.exists(userId)) return null;
7804        flags = updateFlagsForResolve(
7805                flags, userId, intent, callingUid, false /*includeInstantApps*/);
7806        List<ResolveInfo> query = queryIntentServicesInternal(
7807                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
7808        if (query != null) {
7809            if (query.size() >= 1) {
7810                // If there is more than one service with the same priority,
7811                // just arbitrarily pick the first one.
7812                return query.get(0);
7813            }
7814        }
7815        return null;
7816    }
7817
7818    @Override
7819    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7820            String resolvedType, int flags, int userId) {
7821        final int callingUid = Binder.getCallingUid();
7822        return new ParceledListSlice<>(queryIntentServicesInternal(
7823                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
7824    }
7825
7826    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7827            String resolvedType, int flags, int userId, int callingUid,
7828            boolean includeInstantApps) {
7829        if (!sUserManager.exists(userId)) return Collections.emptyList();
7830        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7831        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7832        ComponentName comp = intent.getComponent();
7833        if (comp == null) {
7834            if (intent.getSelector() != null) {
7835                intent = intent.getSelector();
7836                comp = intent.getComponent();
7837            }
7838        }
7839        if (comp != null) {
7840            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7841            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7842            if (si != null) {
7843                // When specifying an explicit component, we prevent the service from being
7844                // used when either 1) the service is in an instant application and the
7845                // caller is not the same instant application or 2) the calling package is
7846                // ephemeral and the activity is not visible to ephemeral applications.
7847                final boolean matchInstantApp =
7848                        (flags & PackageManager.MATCH_INSTANT) != 0;
7849                final boolean matchVisibleToInstantAppOnly =
7850                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7851                final boolean isCallerInstantApp =
7852                        instantAppPkgName != null;
7853                final boolean isTargetSameInstantApp =
7854                        comp.getPackageName().equals(instantAppPkgName);
7855                final boolean isTargetInstantApp =
7856                        (si.applicationInfo.privateFlags
7857                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7858                final boolean isTargetHiddenFromInstantApp =
7859                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7860                final boolean blockResolution =
7861                        !isTargetSameInstantApp
7862                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7863                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7864                                        && isTargetHiddenFromInstantApp));
7865                if (!blockResolution) {
7866                    final ResolveInfo ri = new ResolveInfo();
7867                    ri.serviceInfo = si;
7868                    list.add(ri);
7869                }
7870            }
7871            return list;
7872        }
7873
7874        // reader
7875        synchronized (mPackages) {
7876            String pkgName = intent.getPackage();
7877            if (pkgName == null) {
7878                return applyPostServiceResolutionFilter(
7879                        mServices.queryIntent(intent, resolvedType, flags, userId),
7880                        instantAppPkgName);
7881            }
7882            final PackageParser.Package pkg = mPackages.get(pkgName);
7883            if (pkg != null) {
7884                return applyPostServiceResolutionFilter(
7885                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7886                                userId),
7887                        instantAppPkgName);
7888            }
7889            return Collections.emptyList();
7890        }
7891    }
7892
7893    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
7894            String instantAppPkgName) {
7895        // TODO: When adding on-demand split support for non-instant apps, remove this check
7896        // and always apply post filtering
7897        if (instantAppPkgName == null) {
7898            return resolveInfos;
7899        }
7900        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7901            final ResolveInfo info = resolveInfos.get(i);
7902            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
7903            // allow services that are defined in the provided package
7904            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
7905                if (info.serviceInfo.splitName != null
7906                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
7907                                info.serviceInfo.splitName)) {
7908                    // requested service is defined in a split that hasn't been installed yet.
7909                    // add the installer to the resolve list
7910                    if (DEBUG_EPHEMERAL) {
7911                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7912                    }
7913                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7914                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7915                            info.serviceInfo.packageName, info.serviceInfo.splitName,
7916                            info.serviceInfo.applicationInfo.versionCode, null /*failureIntent*/);
7917                    // make sure this resolver is the default
7918                    installerInfo.isDefault = true;
7919                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7920                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7921                    // add a non-generic filter
7922                    installerInfo.filter = new IntentFilter();
7923                    // load resources from the correct package
7924                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7925                    resolveInfos.set(i, installerInfo);
7926                }
7927                continue;
7928            }
7929            // allow services that have been explicitly exposed to ephemeral apps
7930            if (!isEphemeralApp
7931                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7932                continue;
7933            }
7934            resolveInfos.remove(i);
7935        }
7936        return resolveInfos;
7937    }
7938
7939    @Override
7940    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7941            String resolvedType, int flags, int userId) {
7942        return new ParceledListSlice<>(
7943                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7944    }
7945
7946    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7947            Intent intent, String resolvedType, int flags, int userId) {
7948        if (!sUserManager.exists(userId)) return Collections.emptyList();
7949        final int callingUid = Binder.getCallingUid();
7950        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7951        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7952                false /*includeInstantApps*/);
7953        ComponentName comp = intent.getComponent();
7954        if (comp == null) {
7955            if (intent.getSelector() != null) {
7956                intent = intent.getSelector();
7957                comp = intent.getComponent();
7958            }
7959        }
7960        if (comp != null) {
7961            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7962            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
7963            if (pi != null) {
7964                // When specifying an explicit component, we prevent the provider from being
7965                // used when either 1) the provider is in an instant application and the
7966                // caller is not the same instant application or 2) the calling package is an
7967                // instant application and the provider is not visible to instant applications.
7968                final boolean matchInstantApp =
7969                        (flags & PackageManager.MATCH_INSTANT) != 0;
7970                final boolean matchVisibleToInstantAppOnly =
7971                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7972                final boolean isCallerInstantApp =
7973                        instantAppPkgName != null;
7974                final boolean isTargetSameInstantApp =
7975                        comp.getPackageName().equals(instantAppPkgName);
7976                final boolean isTargetInstantApp =
7977                        (pi.applicationInfo.privateFlags
7978                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7979                final boolean isTargetHiddenFromInstantApp =
7980                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7981                final boolean blockResolution =
7982                        !isTargetSameInstantApp
7983                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7984                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7985                                        && isTargetHiddenFromInstantApp));
7986                if (!blockResolution) {
7987                    final ResolveInfo ri = new ResolveInfo();
7988                    ri.providerInfo = pi;
7989                    list.add(ri);
7990                }
7991            }
7992            return list;
7993        }
7994
7995        // reader
7996        synchronized (mPackages) {
7997            String pkgName = intent.getPackage();
7998            if (pkgName == null) {
7999                return applyPostContentProviderResolutionFilter(
8000                        mProviders.queryIntent(intent, resolvedType, flags, userId),
8001                        instantAppPkgName);
8002            }
8003            final PackageParser.Package pkg = mPackages.get(pkgName);
8004            if (pkg != null) {
8005                return applyPostContentProviderResolutionFilter(
8006                        mProviders.queryIntentForPackage(
8007                        intent, resolvedType, flags, pkg.providers, userId),
8008                        instantAppPkgName);
8009            }
8010            return Collections.emptyList();
8011        }
8012    }
8013
8014    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
8015            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
8016        // TODO: When adding on-demand split support for non-instant applications, remove
8017        // this check and always apply post filtering
8018        if (instantAppPkgName == null) {
8019            return resolveInfos;
8020        }
8021        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
8022            final ResolveInfo info = resolveInfos.get(i);
8023            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
8024            // allow providers that are defined in the provided package
8025            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
8026                if (info.providerInfo.splitName != null
8027                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
8028                                info.providerInfo.splitName)) {
8029                    // requested provider is defined in a split that hasn't been installed yet.
8030                    // add the installer to the resolve list
8031                    if (DEBUG_EPHEMERAL) {
8032                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
8033                    }
8034                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
8035                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
8036                            info.providerInfo.packageName, info.providerInfo.splitName,
8037                            info.providerInfo.applicationInfo.versionCode, null /*failureIntent*/);
8038                    // make sure this resolver is the default
8039                    installerInfo.isDefault = true;
8040                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
8041                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
8042                    // add a non-generic filter
8043                    installerInfo.filter = new IntentFilter();
8044                    // load resources from the correct package
8045                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
8046                    resolveInfos.set(i, installerInfo);
8047                }
8048                continue;
8049            }
8050            // allow providers that have been explicitly exposed to instant applications
8051            if (!isEphemeralApp
8052                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
8053                continue;
8054            }
8055            resolveInfos.remove(i);
8056        }
8057        return resolveInfos;
8058    }
8059
8060    @Override
8061    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
8062        final int callingUid = Binder.getCallingUid();
8063        if (getInstantAppPackageName(callingUid) != null) {
8064            return ParceledListSlice.emptyList();
8065        }
8066        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8067        flags = updateFlagsForPackage(flags, userId, null);
8068        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8069        enforceCrossUserPermission(callingUid, userId,
8070                true /* requireFullPermission */, false /* checkShell */,
8071                "get installed packages");
8072
8073        // writer
8074        synchronized (mPackages) {
8075            ArrayList<PackageInfo> list;
8076            if (listUninstalled) {
8077                list = new ArrayList<>(mSettings.mPackages.size());
8078                for (PackageSetting ps : mSettings.mPackages.values()) {
8079                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8080                        continue;
8081                    }
8082                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8083                        return null;
8084                    }
8085                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8086                    if (pi != null) {
8087                        list.add(pi);
8088                    }
8089                }
8090            } else {
8091                list = new ArrayList<>(mPackages.size());
8092                for (PackageParser.Package p : mPackages.values()) {
8093                    final PackageSetting ps = (PackageSetting) p.mExtras;
8094                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8095                        continue;
8096                    }
8097                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8098                        return null;
8099                    }
8100                    final PackageInfo pi = generatePackageInfo((PackageSetting)
8101                            p.mExtras, flags, userId);
8102                    if (pi != null) {
8103                        list.add(pi);
8104                    }
8105                }
8106            }
8107
8108            return new ParceledListSlice<>(list);
8109        }
8110    }
8111
8112    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
8113            String[] permissions, boolean[] tmp, int flags, int userId) {
8114        int numMatch = 0;
8115        final PermissionsState permissionsState = ps.getPermissionsState();
8116        for (int i=0; i<permissions.length; i++) {
8117            final String permission = permissions[i];
8118            if (permissionsState.hasPermission(permission, userId)) {
8119                tmp[i] = true;
8120                numMatch++;
8121            } else {
8122                tmp[i] = false;
8123            }
8124        }
8125        if (numMatch == 0) {
8126            return;
8127        }
8128        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8129
8130        // The above might return null in cases of uninstalled apps or install-state
8131        // skew across users/profiles.
8132        if (pi != null) {
8133            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
8134                if (numMatch == permissions.length) {
8135                    pi.requestedPermissions = permissions;
8136                } else {
8137                    pi.requestedPermissions = new String[numMatch];
8138                    numMatch = 0;
8139                    for (int i=0; i<permissions.length; i++) {
8140                        if (tmp[i]) {
8141                            pi.requestedPermissions[numMatch] = permissions[i];
8142                            numMatch++;
8143                        }
8144                    }
8145                }
8146            }
8147            list.add(pi);
8148        }
8149    }
8150
8151    @Override
8152    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
8153            String[] permissions, int flags, int userId) {
8154        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8155        flags = updateFlagsForPackage(flags, userId, permissions);
8156        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8157                true /* requireFullPermission */, false /* checkShell */,
8158                "get packages holding permissions");
8159        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8160
8161        // writer
8162        synchronized (mPackages) {
8163            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
8164            boolean[] tmpBools = new boolean[permissions.length];
8165            if (listUninstalled) {
8166                for (PackageSetting ps : mSettings.mPackages.values()) {
8167                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8168                            userId);
8169                }
8170            } else {
8171                for (PackageParser.Package pkg : mPackages.values()) {
8172                    PackageSetting ps = (PackageSetting)pkg.mExtras;
8173                    if (ps != null) {
8174                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8175                                userId);
8176                    }
8177                }
8178            }
8179
8180            return new ParceledListSlice<PackageInfo>(list);
8181        }
8182    }
8183
8184    @Override
8185    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
8186        final int callingUid = Binder.getCallingUid();
8187        if (getInstantAppPackageName(callingUid) != null) {
8188            return ParceledListSlice.emptyList();
8189        }
8190        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8191        flags = updateFlagsForApplication(flags, userId, null);
8192        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8193
8194        // writer
8195        synchronized (mPackages) {
8196            ArrayList<ApplicationInfo> list;
8197            if (listUninstalled) {
8198                list = new ArrayList<>(mSettings.mPackages.size());
8199                for (PackageSetting ps : mSettings.mPackages.values()) {
8200                    ApplicationInfo ai;
8201                    int effectiveFlags = flags;
8202                    if (ps.isSystem()) {
8203                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
8204                    }
8205                    if (ps.pkg != null) {
8206                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8207                            continue;
8208                        }
8209                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8210                            return null;
8211                        }
8212                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
8213                                ps.readUserState(userId), userId);
8214                        if (ai != null) {
8215                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
8216                        }
8217                    } else {
8218                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
8219                        // and already converts to externally visible package name
8220                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
8221                                callingUid, effectiveFlags, userId);
8222                    }
8223                    if (ai != null) {
8224                        list.add(ai);
8225                    }
8226                }
8227            } else {
8228                list = new ArrayList<>(mPackages.size());
8229                for (PackageParser.Package p : mPackages.values()) {
8230                    if (p.mExtras != null) {
8231                        PackageSetting ps = (PackageSetting) p.mExtras;
8232                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
8233                            continue;
8234                        }
8235                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8236                            return null;
8237                        }
8238                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8239                                ps.readUserState(userId), userId);
8240                        if (ai != null) {
8241                            ai.packageName = resolveExternalPackageNameLPr(p);
8242                            list.add(ai);
8243                        }
8244                    }
8245                }
8246            }
8247
8248            return new ParceledListSlice<>(list);
8249        }
8250    }
8251
8252    @Override
8253    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
8254        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8255            return null;
8256        }
8257        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8258                "getEphemeralApplications");
8259        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8260                true /* requireFullPermission */, false /* checkShell */,
8261                "getEphemeralApplications");
8262        synchronized (mPackages) {
8263            List<InstantAppInfo> instantApps = mInstantAppRegistry
8264                    .getInstantAppsLPr(userId);
8265            if (instantApps != null) {
8266                return new ParceledListSlice<>(instantApps);
8267            }
8268        }
8269        return null;
8270    }
8271
8272    @Override
8273    public boolean isInstantApp(String packageName, int userId) {
8274        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8275                true /* requireFullPermission */, false /* checkShell */,
8276                "isInstantApp");
8277        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8278            return false;
8279        }
8280        int callingUid = Binder.getCallingUid();
8281        if (Process.isIsolated(callingUid)) {
8282            callingUid = mIsolatedOwners.get(callingUid);
8283        }
8284
8285        synchronized (mPackages) {
8286            final PackageSetting ps = mSettings.mPackages.get(packageName);
8287            PackageParser.Package pkg = mPackages.get(packageName);
8288            final boolean returnAllowed =
8289                    ps != null
8290                    && (isCallerSameApp(packageName, callingUid)
8291                            || canViewInstantApps(callingUid, userId)
8292                            || mInstantAppRegistry.isInstantAccessGranted(
8293                                    userId, UserHandle.getAppId(callingUid), ps.appId));
8294            if (returnAllowed) {
8295                return ps.getInstantApp(userId);
8296            }
8297        }
8298        return false;
8299    }
8300
8301    @Override
8302    public byte[] getInstantAppCookie(String packageName, int userId) {
8303        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8304            return null;
8305        }
8306
8307        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8308                true /* requireFullPermission */, false /* checkShell */,
8309                "getInstantAppCookie");
8310        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8311            return null;
8312        }
8313        synchronized (mPackages) {
8314            return mInstantAppRegistry.getInstantAppCookieLPw(
8315                    packageName, userId);
8316        }
8317    }
8318
8319    @Override
8320    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8321        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8322            return true;
8323        }
8324
8325        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8326                true /* requireFullPermission */, true /* checkShell */,
8327                "setInstantAppCookie");
8328        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8329            return false;
8330        }
8331        synchronized (mPackages) {
8332            return mInstantAppRegistry.setInstantAppCookieLPw(
8333                    packageName, cookie, userId);
8334        }
8335    }
8336
8337    @Override
8338    public Bitmap getInstantAppIcon(String packageName, int userId) {
8339        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8340            return null;
8341        }
8342
8343        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8344                "getInstantAppIcon");
8345
8346        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8347                true /* requireFullPermission */, false /* checkShell */,
8348                "getInstantAppIcon");
8349
8350        synchronized (mPackages) {
8351            return mInstantAppRegistry.getInstantAppIconLPw(
8352                    packageName, userId);
8353        }
8354    }
8355
8356    private boolean isCallerSameApp(String packageName, int uid) {
8357        PackageParser.Package pkg = mPackages.get(packageName);
8358        return pkg != null
8359                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8360    }
8361
8362    @Override
8363    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8364        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8365            return ParceledListSlice.emptyList();
8366        }
8367        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8368    }
8369
8370    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8371        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8372
8373        // reader
8374        synchronized (mPackages) {
8375            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8376            final int userId = UserHandle.getCallingUserId();
8377            while (i.hasNext()) {
8378                final PackageParser.Package p = i.next();
8379                if (p.applicationInfo == null) continue;
8380
8381                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8382                        && !p.applicationInfo.isDirectBootAware();
8383                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8384                        && p.applicationInfo.isDirectBootAware();
8385
8386                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8387                        && (!mSafeMode || isSystemApp(p))
8388                        && (matchesUnaware || matchesAware)) {
8389                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
8390                    if (ps != null) {
8391                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8392                                ps.readUserState(userId), userId);
8393                        if (ai != null) {
8394                            finalList.add(ai);
8395                        }
8396                    }
8397                }
8398            }
8399        }
8400
8401        return finalList;
8402    }
8403
8404    @Override
8405    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8406        if (!sUserManager.exists(userId)) return null;
8407        flags = updateFlagsForComponent(flags, userId, name);
8408        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
8409        // reader
8410        synchronized (mPackages) {
8411            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8412            PackageSetting ps = provider != null
8413                    ? mSettings.mPackages.get(provider.owner.packageName)
8414                    : null;
8415            if (ps != null) {
8416                final boolean isInstantApp = ps.getInstantApp(userId);
8417                // normal application; filter out instant application provider
8418                if (instantAppPkgName == null && isInstantApp) {
8419                    return null;
8420                }
8421                // instant application; filter out other instant applications
8422                if (instantAppPkgName != null
8423                        && isInstantApp
8424                        && !provider.owner.packageName.equals(instantAppPkgName)) {
8425                    return null;
8426                }
8427                // instant application; filter out non-exposed provider
8428                if (instantAppPkgName != null
8429                        && !isInstantApp
8430                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
8431                    return null;
8432                }
8433                // provider not enabled
8434                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8435                    return null;
8436                }
8437                return PackageParser.generateProviderInfo(
8438                        provider, flags, ps.readUserState(userId), userId);
8439            }
8440            return null;
8441        }
8442    }
8443
8444    /**
8445     * @deprecated
8446     */
8447    @Deprecated
8448    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8449        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8450            return;
8451        }
8452        // reader
8453        synchronized (mPackages) {
8454            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8455                    .entrySet().iterator();
8456            final int userId = UserHandle.getCallingUserId();
8457            while (i.hasNext()) {
8458                Map.Entry<String, PackageParser.Provider> entry = i.next();
8459                PackageParser.Provider p = entry.getValue();
8460                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8461
8462                if (ps != null && p.syncable
8463                        && (!mSafeMode || (p.info.applicationInfo.flags
8464                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8465                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8466                            ps.readUserState(userId), userId);
8467                    if (info != null) {
8468                        outNames.add(entry.getKey());
8469                        outInfo.add(info);
8470                    }
8471                }
8472            }
8473        }
8474    }
8475
8476    @Override
8477    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8478            int uid, int flags, String metaDataKey) {
8479        final int callingUid = Binder.getCallingUid();
8480        final int userId = processName != null ? UserHandle.getUserId(uid)
8481                : UserHandle.getCallingUserId();
8482        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8483        flags = updateFlagsForComponent(flags, userId, processName);
8484        ArrayList<ProviderInfo> finalList = null;
8485        // reader
8486        synchronized (mPackages) {
8487            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8488            while (i.hasNext()) {
8489                final PackageParser.Provider p = i.next();
8490                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8491                if (ps != null && p.info.authority != null
8492                        && (processName == null
8493                                || (p.info.processName.equals(processName)
8494                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8495                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8496
8497                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8498                    // parameter.
8499                    if (metaDataKey != null
8500                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8501                        continue;
8502                    }
8503                    final ComponentName component =
8504                            new ComponentName(p.info.packageName, p.info.name);
8505                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8506                        continue;
8507                    }
8508                    if (finalList == null) {
8509                        finalList = new ArrayList<ProviderInfo>(3);
8510                    }
8511                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8512                            ps.readUserState(userId), userId);
8513                    if (info != null) {
8514                        finalList.add(info);
8515                    }
8516                }
8517            }
8518        }
8519
8520        if (finalList != null) {
8521            Collections.sort(finalList, mProviderInitOrderSorter);
8522            return new ParceledListSlice<ProviderInfo>(finalList);
8523        }
8524
8525        return ParceledListSlice.emptyList();
8526    }
8527
8528    @Override
8529    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8530        // reader
8531        synchronized (mPackages) {
8532            final int callingUid = Binder.getCallingUid();
8533            final int callingUserId = UserHandle.getUserId(callingUid);
8534            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8535            if (ps == null) return null;
8536            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8537                return null;
8538            }
8539            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8540            return PackageParser.generateInstrumentationInfo(i, flags);
8541        }
8542    }
8543
8544    @Override
8545    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8546            String targetPackage, int flags) {
8547        final int callingUid = Binder.getCallingUid();
8548        final int callingUserId = UserHandle.getUserId(callingUid);
8549        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8550        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8551            return ParceledListSlice.emptyList();
8552        }
8553        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8554    }
8555
8556    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8557            int flags) {
8558        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8559
8560        // reader
8561        synchronized (mPackages) {
8562            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8563            while (i.hasNext()) {
8564                final PackageParser.Instrumentation p = i.next();
8565                if (targetPackage == null
8566                        || targetPackage.equals(p.info.targetPackage)) {
8567                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8568                            flags);
8569                    if (ii != null) {
8570                        finalList.add(ii);
8571                    }
8572                }
8573            }
8574        }
8575
8576        return finalList;
8577    }
8578
8579    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
8580        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
8581        try {
8582            scanDirLI(dir, parseFlags, scanFlags, currentTime);
8583        } finally {
8584            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8585        }
8586    }
8587
8588    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
8589        final File[] files = dir.listFiles();
8590        if (ArrayUtils.isEmpty(files)) {
8591            Log.d(TAG, "No files in app dir " + dir);
8592            return;
8593        }
8594
8595        if (DEBUG_PACKAGE_SCANNING) {
8596            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
8597                    + " flags=0x" + Integer.toHexString(parseFlags));
8598        }
8599        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
8600                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
8601                mParallelPackageParserCallback);
8602
8603        // Submit files for parsing in parallel
8604        int fileCount = 0;
8605        for (File file : files) {
8606            final boolean isPackage = (isApkFile(file) || file.isDirectory())
8607                    && !PackageInstallerService.isStageName(file.getName());
8608            if (!isPackage) {
8609                // Ignore entries which are not packages
8610                continue;
8611            }
8612            parallelPackageParser.submit(file, parseFlags);
8613            fileCount++;
8614        }
8615
8616        // Process results one by one
8617        for (; fileCount > 0; fileCount--) {
8618            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
8619            Throwable throwable = parseResult.throwable;
8620            int errorCode = PackageManager.INSTALL_SUCCEEDED;
8621
8622            if (throwable == null) {
8623                // Static shared libraries have synthetic package names
8624                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
8625                    renameStaticSharedLibraryPackage(parseResult.pkg);
8626                }
8627                try {
8628                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
8629                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
8630                                currentTime, null);
8631                    }
8632                } catch (PackageManagerException e) {
8633                    errorCode = e.error;
8634                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
8635                }
8636            } else if (throwable instanceof PackageParser.PackageParserException) {
8637                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
8638                        throwable;
8639                errorCode = e.error;
8640                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
8641            } else {
8642                throw new IllegalStateException("Unexpected exception occurred while parsing "
8643                        + parseResult.scanFile, throwable);
8644            }
8645
8646            // Delete invalid userdata apps
8647            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
8648                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
8649                logCriticalInfo(Log.WARN,
8650                        "Deleting invalid package at " + parseResult.scanFile);
8651                removeCodePathLI(parseResult.scanFile);
8652            }
8653        }
8654        parallelPackageParser.close();
8655    }
8656
8657    private static File getSettingsProblemFile() {
8658        File dataDir = Environment.getDataDirectory();
8659        File systemDir = new File(dataDir, "system");
8660        File fname = new File(systemDir, "uiderrors.txt");
8661        return fname;
8662    }
8663
8664    static void reportSettingsProblem(int priority, String msg) {
8665        logCriticalInfo(priority, msg);
8666    }
8667
8668    public static void logCriticalInfo(int priority, String msg) {
8669        Slog.println(priority, TAG, msg);
8670        EventLogTags.writePmCriticalInfo(msg);
8671        try {
8672            File fname = getSettingsProblemFile();
8673            FileOutputStream out = new FileOutputStream(fname, true);
8674            PrintWriter pw = new FastPrintWriter(out);
8675            SimpleDateFormat formatter = new SimpleDateFormat();
8676            String dateString = formatter.format(new Date(System.currentTimeMillis()));
8677            pw.println(dateString + ": " + msg);
8678            pw.close();
8679            FileUtils.setPermissions(
8680                    fname.toString(),
8681                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
8682                    -1, -1);
8683        } catch (java.io.IOException e) {
8684        }
8685    }
8686
8687    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
8688        if (srcFile.isDirectory()) {
8689            final File baseFile = new File(pkg.baseCodePath);
8690            long maxModifiedTime = baseFile.lastModified();
8691            if (pkg.splitCodePaths != null) {
8692                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
8693                    final File splitFile = new File(pkg.splitCodePaths[i]);
8694                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
8695                }
8696            }
8697            return maxModifiedTime;
8698        }
8699        return srcFile.lastModified();
8700    }
8701
8702    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
8703            final int policyFlags) throws PackageManagerException {
8704        // When upgrading from pre-N MR1, verify the package time stamp using the package
8705        // directory and not the APK file.
8706        final long lastModifiedTime = mIsPreNMR1Upgrade
8707                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
8708        if (ps != null
8709                && ps.codePath.equals(srcFile)
8710                && ps.timeStamp == lastModifiedTime
8711                && !isCompatSignatureUpdateNeeded(pkg)
8712                && !isRecoverSignatureUpdateNeeded(pkg)) {
8713            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
8714            KeySetManagerService ksms = mSettings.mKeySetManagerService;
8715            ArraySet<PublicKey> signingKs;
8716            synchronized (mPackages) {
8717                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
8718            }
8719            if (ps.signatures.mSignatures != null
8720                    && ps.signatures.mSignatures.length != 0
8721                    && signingKs != null) {
8722                // Optimization: reuse the existing cached certificates
8723                // if the package appears to be unchanged.
8724                pkg.mSignatures = ps.signatures.mSignatures;
8725                pkg.mSigningKeys = signingKs;
8726                return;
8727            }
8728
8729            Slog.w(TAG, "PackageSetting for " + ps.name
8730                    + " is missing signatures.  Collecting certs again to recover them.");
8731        } else {
8732            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
8733        }
8734
8735        try {
8736            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
8737            PackageParser.collectCertificates(pkg, policyFlags);
8738        } catch (PackageParserException e) {
8739            throw PackageManagerException.from(e);
8740        } finally {
8741            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8742        }
8743    }
8744
8745    /**
8746     *  Traces a package scan.
8747     *  @see #scanPackageLI(File, int, int, long, UserHandle)
8748     */
8749    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
8750            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8751        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
8752        try {
8753            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
8754        } finally {
8755            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8756        }
8757    }
8758
8759    /**
8760     *  Scans a package and returns the newly parsed package.
8761     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
8762     */
8763    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
8764            long currentTime, UserHandle user) throws PackageManagerException {
8765        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
8766        PackageParser pp = new PackageParser();
8767        pp.setSeparateProcesses(mSeparateProcesses);
8768        pp.setOnlyCoreApps(mOnlyCore);
8769        pp.setDisplayMetrics(mMetrics);
8770        pp.setCallback(mPackageParserCallback);
8771
8772        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
8773            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
8774        }
8775
8776        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
8777        final PackageParser.Package pkg;
8778        try {
8779            pkg = pp.parsePackage(scanFile, parseFlags);
8780        } catch (PackageParserException e) {
8781            throw PackageManagerException.from(e);
8782        } finally {
8783            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8784        }
8785
8786        // Static shared libraries have synthetic package names
8787        if (pkg.applicationInfo.isStaticSharedLibrary()) {
8788            renameStaticSharedLibraryPackage(pkg);
8789        }
8790
8791        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
8792    }
8793
8794    /**
8795     *  Scans a package and returns the newly parsed package.
8796     *  @throws PackageManagerException on a parse error.
8797     */
8798    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
8799            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8800            throws PackageManagerException {
8801        // If the package has children and this is the first dive in the function
8802        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
8803        // packages (parent and children) would be successfully scanned before the
8804        // actual scan since scanning mutates internal state and we want to atomically
8805        // install the package and its children.
8806        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8807            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8808                scanFlags |= SCAN_CHECK_ONLY;
8809            }
8810        } else {
8811            scanFlags &= ~SCAN_CHECK_ONLY;
8812        }
8813
8814        // Scan the parent
8815        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
8816                scanFlags, currentTime, user);
8817
8818        // Scan the children
8819        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8820        for (int i = 0; i < childCount; i++) {
8821            PackageParser.Package childPackage = pkg.childPackages.get(i);
8822            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
8823                    currentTime, user);
8824        }
8825
8826
8827        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8828            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
8829        }
8830
8831        return scannedPkg;
8832    }
8833
8834    /**
8835     *  Scans a package and returns the newly parsed package.
8836     *  @throws PackageManagerException on a parse error.
8837     */
8838    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
8839            int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8840            throws PackageManagerException {
8841        PackageSetting ps = null;
8842        PackageSetting updatedPkg;
8843        // reader
8844        synchronized (mPackages) {
8845            // Look to see if we already know about this package.
8846            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
8847            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
8848                // This package has been renamed to its original name.  Let's
8849                // use that.
8850                ps = mSettings.getPackageLPr(oldName);
8851            }
8852            // If there was no original package, see one for the real package name.
8853            if (ps == null) {
8854                ps = mSettings.getPackageLPr(pkg.packageName);
8855            }
8856            // Check to see if this package could be hiding/updating a system
8857            // package.  Must look for it either under the original or real
8858            // package name depending on our state.
8859            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
8860            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
8861
8862            // If this is a package we don't know about on the system partition, we
8863            // may need to remove disabled child packages on the system partition
8864            // or may need to not add child packages if the parent apk is updated
8865            // on the data partition and no longer defines this child package.
8866            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
8867                // If this is a parent package for an updated system app and this system
8868                // app got an OTA update which no longer defines some of the child packages
8869                // we have to prune them from the disabled system packages.
8870                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8871                if (disabledPs != null) {
8872                    final int scannedChildCount = (pkg.childPackages != null)
8873                            ? pkg.childPackages.size() : 0;
8874                    final int disabledChildCount = disabledPs.childPackageNames != null
8875                            ? disabledPs.childPackageNames.size() : 0;
8876                    for (int i = 0; i < disabledChildCount; i++) {
8877                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
8878                        boolean disabledPackageAvailable = false;
8879                        for (int j = 0; j < scannedChildCount; j++) {
8880                            PackageParser.Package childPkg = pkg.childPackages.get(j);
8881                            if (childPkg.packageName.equals(disabledChildPackageName)) {
8882                                disabledPackageAvailable = true;
8883                                break;
8884                            }
8885                         }
8886                         if (!disabledPackageAvailable) {
8887                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
8888                         }
8889                    }
8890                }
8891            }
8892        }
8893
8894        boolean updatedPkgBetter = false;
8895        // First check if this is a system package that may involve an update
8896        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
8897            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
8898            // it needs to drop FLAG_PRIVILEGED.
8899            if (locationIsPrivileged(scanFile)) {
8900                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8901            } else {
8902                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8903            }
8904
8905            if (ps != null && !ps.codePath.equals(scanFile)) {
8906                // The path has changed from what was last scanned...  check the
8907                // version of the new path against what we have stored to determine
8908                // what to do.
8909                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
8910                if (pkg.mVersionCode <= ps.versionCode) {
8911                    // The system package has been updated and the code path does not match
8912                    // Ignore entry. Skip it.
8913                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
8914                            + " ignored: updated version " + ps.versionCode
8915                            + " better than this " + pkg.mVersionCode);
8916                    if (!updatedPkg.codePath.equals(scanFile)) {
8917                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
8918                                + ps.name + " changing from " + updatedPkg.codePathString
8919                                + " to " + scanFile);
8920                        updatedPkg.codePath = scanFile;
8921                        updatedPkg.codePathString = scanFile.toString();
8922                        updatedPkg.resourcePath = scanFile;
8923                        updatedPkg.resourcePathString = scanFile.toString();
8924                    }
8925                    updatedPkg.pkg = pkg;
8926                    updatedPkg.versionCode = pkg.mVersionCode;
8927
8928                    // Update the disabled system child packages to point to the package too.
8929                    final int childCount = updatedPkg.childPackageNames != null
8930                            ? updatedPkg.childPackageNames.size() : 0;
8931                    for (int i = 0; i < childCount; i++) {
8932                        String childPackageName = updatedPkg.childPackageNames.get(i);
8933                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
8934                                childPackageName);
8935                        if (updatedChildPkg != null) {
8936                            updatedChildPkg.pkg = pkg;
8937                            updatedChildPkg.versionCode = pkg.mVersionCode;
8938                        }
8939                    }
8940
8941                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
8942                            + scanFile + " ignored: updated version " + ps.versionCode
8943                            + " better than this " + pkg.mVersionCode);
8944                } else {
8945                    // The current app on the system partition is better than
8946                    // what we have updated to on the data partition; switch
8947                    // back to the system partition version.
8948                    // At this point, its safely assumed that package installation for
8949                    // apps in system partition will go through. If not there won't be a working
8950                    // version of the app
8951                    // writer
8952                    synchronized (mPackages) {
8953                        // Just remove the loaded entries from package lists.
8954                        mPackages.remove(ps.name);
8955                    }
8956
8957                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
8958                            + " reverting from " + ps.codePathString
8959                            + ": new version " + pkg.mVersionCode
8960                            + " better than installed " + ps.versionCode);
8961
8962                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
8963                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
8964                    synchronized (mInstallLock) {
8965                        args.cleanUpResourcesLI();
8966                    }
8967                    synchronized (mPackages) {
8968                        mSettings.enableSystemPackageLPw(ps.name);
8969                    }
8970                    updatedPkgBetter = true;
8971                }
8972            }
8973        }
8974
8975        if (updatedPkg != null) {
8976            // An updated system app will not have the PARSE_IS_SYSTEM flag set
8977            // initially
8978            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
8979
8980            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
8981            // flag set initially
8982            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
8983                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
8984            }
8985        }
8986
8987        // Verify certificates against what was last scanned
8988        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
8989
8990        /*
8991         * A new system app appeared, but we already had a non-system one of the
8992         * same name installed earlier.
8993         */
8994        boolean shouldHideSystemApp = false;
8995        if (updatedPkg == null && ps != null
8996                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
8997            /*
8998             * Check to make sure the signatures match first. If they don't,
8999             * wipe the installed application and its data.
9000             */
9001            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
9002                    != PackageManager.SIGNATURE_MATCH) {
9003                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
9004                        + " signatures don't match existing userdata copy; removing");
9005                try (PackageFreezer freezer = freezePackage(pkg.packageName,
9006                        "scanPackageInternalLI")) {
9007                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
9008                }
9009                ps = null;
9010            } else {
9011                /*
9012                 * If the newly-added system app is an older version than the
9013                 * already installed version, hide it. It will be scanned later
9014                 * and re-added like an update.
9015                 */
9016                if (pkg.mVersionCode <= ps.versionCode) {
9017                    shouldHideSystemApp = true;
9018                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
9019                            + " but new version " + pkg.mVersionCode + " better than installed "
9020                            + ps.versionCode + "; hiding system");
9021                } else {
9022                    /*
9023                     * The newly found system app is a newer version that the
9024                     * one previously installed. Simply remove the
9025                     * already-installed application and replace it with our own
9026                     * while keeping the application data.
9027                     */
9028                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
9029                            + " reverting from " + ps.codePathString + ": new version "
9030                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
9031                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
9032                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
9033                    synchronized (mInstallLock) {
9034                        args.cleanUpResourcesLI();
9035                    }
9036                }
9037            }
9038        }
9039
9040        // The apk is forward locked (not public) if its code and resources
9041        // are kept in different files. (except for app in either system or
9042        // vendor path).
9043        // TODO grab this value from PackageSettings
9044        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9045            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
9046                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
9047            }
9048        }
9049
9050        // TODO: extend to support forward-locked splits
9051        String resourcePath = null;
9052        String baseResourcePath = null;
9053        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
9054            if (ps != null && ps.resourcePathString != null) {
9055                resourcePath = ps.resourcePathString;
9056                baseResourcePath = ps.resourcePathString;
9057            } else {
9058                // Should not happen at all. Just log an error.
9059                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
9060            }
9061        } else {
9062            resourcePath = pkg.codePath;
9063            baseResourcePath = pkg.baseCodePath;
9064        }
9065
9066        // Set application objects path explicitly.
9067        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
9068        pkg.setApplicationInfoCodePath(pkg.codePath);
9069        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
9070        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
9071        pkg.setApplicationInfoResourcePath(resourcePath);
9072        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
9073        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
9074
9075        final int userId = ((user == null) ? 0 : user.getIdentifier());
9076        if (ps != null && ps.getInstantApp(userId)) {
9077            scanFlags |= SCAN_AS_INSTANT_APP;
9078        }
9079
9080        // Note that we invoke the following method only if we are about to unpack an application
9081        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
9082                | SCAN_UPDATE_SIGNATURE, currentTime, user);
9083
9084        /*
9085         * If the system app should be overridden by a previously installed
9086         * data, hide the system app now and let the /data/app scan pick it up
9087         * again.
9088         */
9089        if (shouldHideSystemApp) {
9090            synchronized (mPackages) {
9091                mSettings.disableSystemPackageLPw(pkg.packageName, true);
9092            }
9093        }
9094
9095        return scannedPkg;
9096    }
9097
9098    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
9099        // Derive the new package synthetic package name
9100        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
9101                + pkg.staticSharedLibVersion);
9102    }
9103
9104    private static String fixProcessName(String defProcessName,
9105            String processName) {
9106        if (processName == null) {
9107            return defProcessName;
9108        }
9109        return processName;
9110    }
9111
9112    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
9113            throws PackageManagerException {
9114        if (pkgSetting.signatures.mSignatures != null) {
9115            // Already existing package. Make sure signatures match
9116            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
9117                    == PackageManager.SIGNATURE_MATCH;
9118            if (!match) {
9119                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
9120                        == PackageManager.SIGNATURE_MATCH;
9121            }
9122            if (!match) {
9123                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
9124                        == PackageManager.SIGNATURE_MATCH;
9125            }
9126            if (!match) {
9127                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
9128                        + pkg.packageName + " signatures do not match the "
9129                        + "previously installed version; ignoring!");
9130            }
9131        }
9132
9133        // Check for shared user signatures
9134        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
9135            // Already existing package. Make sure signatures match
9136            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
9137                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
9138            if (!match) {
9139                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
9140                        == PackageManager.SIGNATURE_MATCH;
9141            }
9142            if (!match) {
9143                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
9144                        == PackageManager.SIGNATURE_MATCH;
9145            }
9146            if (!match) {
9147                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
9148                        "Package " + pkg.packageName
9149                        + " has no signatures that match those in shared user "
9150                        + pkgSetting.sharedUser.name + "; ignoring!");
9151            }
9152        }
9153    }
9154
9155    /**
9156     * Enforces that only the system UID or root's UID can call a method exposed
9157     * via Binder.
9158     *
9159     * @param message used as message if SecurityException is thrown
9160     * @throws SecurityException if the caller is not system or root
9161     */
9162    private static final void enforceSystemOrRoot(String message) {
9163        final int uid = Binder.getCallingUid();
9164        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
9165            throw new SecurityException(message);
9166        }
9167    }
9168
9169    @Override
9170    public void performFstrimIfNeeded() {
9171        enforceSystemOrRoot("Only the system can request fstrim");
9172
9173        // Before everything else, see whether we need to fstrim.
9174        try {
9175            IStorageManager sm = PackageHelper.getStorageManager();
9176            if (sm != null) {
9177                boolean doTrim = false;
9178                final long interval = android.provider.Settings.Global.getLong(
9179                        mContext.getContentResolver(),
9180                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
9181                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
9182                if (interval > 0) {
9183                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
9184                    if (timeSinceLast > interval) {
9185                        doTrim = true;
9186                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
9187                                + "; running immediately");
9188                    }
9189                }
9190                if (doTrim) {
9191                    final boolean dexOptDialogShown;
9192                    synchronized (mPackages) {
9193                        dexOptDialogShown = mDexOptDialogShown;
9194                    }
9195                    if (!isFirstBoot() && dexOptDialogShown) {
9196                        try {
9197                            ActivityManager.getService().showBootMessage(
9198                                    mContext.getResources().getString(
9199                                            R.string.android_upgrading_fstrim), true);
9200                        } catch (RemoteException e) {
9201                        }
9202                    }
9203                    sm.runMaintenance();
9204                }
9205            } else {
9206                Slog.e(TAG, "storageManager service unavailable!");
9207            }
9208        } catch (RemoteException e) {
9209            // Can't happen; StorageManagerService is local
9210        }
9211    }
9212
9213    @Override
9214    public void updatePackagesIfNeeded() {
9215        enforceSystemOrRoot("Only the system can request package update");
9216
9217        // We need to re-extract after an OTA.
9218        boolean causeUpgrade = isUpgrade();
9219
9220        // First boot or factory reset.
9221        // Note: we also handle devices that are upgrading to N right now as if it is their
9222        //       first boot, as they do not have profile data.
9223        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
9224
9225        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
9226        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
9227
9228        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
9229            return;
9230        }
9231
9232        List<PackageParser.Package> pkgs;
9233        synchronized (mPackages) {
9234            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
9235        }
9236
9237        final long startTime = System.nanoTime();
9238        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
9239                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT),
9240                    false /* bootComplete */);
9241
9242        final int elapsedTimeSeconds =
9243                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
9244
9245        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
9246        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
9247        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
9248        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
9249        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
9250    }
9251
9252    /**
9253     * Performs dexopt on the set of packages in {@code packages} and returns an int array
9254     * containing statistics about the invocation. The array consists of three elements,
9255     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
9256     * and {@code numberOfPackagesFailed}.
9257     */
9258    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
9259            String compilerFilter, boolean bootComplete) {
9260
9261        int numberOfPackagesVisited = 0;
9262        int numberOfPackagesOptimized = 0;
9263        int numberOfPackagesSkipped = 0;
9264        int numberOfPackagesFailed = 0;
9265        final int numberOfPackagesToDexopt = pkgs.size();
9266
9267        for (PackageParser.Package pkg : pkgs) {
9268            numberOfPackagesVisited++;
9269
9270            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
9271                if (DEBUG_DEXOPT) {
9272                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
9273                }
9274                numberOfPackagesSkipped++;
9275                continue;
9276            }
9277
9278            if (DEBUG_DEXOPT) {
9279                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
9280                        numberOfPackagesToDexopt + ": " + pkg.packageName);
9281            }
9282
9283            if (showDialog) {
9284                try {
9285                    ActivityManager.getService().showBootMessage(
9286                            mContext.getResources().getString(R.string.android_upgrading_apk,
9287                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
9288                } catch (RemoteException e) {
9289                }
9290                synchronized (mPackages) {
9291                    mDexOptDialogShown = true;
9292                }
9293            }
9294
9295            // If the OTA updates a system app which was previously preopted to a non-preopted state
9296            // the app might end up being verified at runtime. That's because by default the apps
9297            // are verify-profile but for preopted apps there's no profile.
9298            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
9299            // that before the OTA the app was preopted) the app gets compiled with a non-profile
9300            // filter (by default 'quicken').
9301            // Note that at this stage unused apps are already filtered.
9302            if (isSystemApp(pkg) &&
9303                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
9304                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
9305                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
9306            }
9307
9308            // checkProfiles is false to avoid merging profiles during boot which
9309            // might interfere with background compilation (b/28612421).
9310            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
9311            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
9312            // trade-off worth doing to save boot time work.
9313            int dexOptStatus = performDexOptTraced(pkg.packageName,
9314                    false /* checkProfiles */,
9315                    compilerFilter,
9316                    false /* force */,
9317                    bootComplete);
9318            switch (dexOptStatus) {
9319                case PackageDexOptimizer.DEX_OPT_PERFORMED:
9320                    numberOfPackagesOptimized++;
9321                    break;
9322                case PackageDexOptimizer.DEX_OPT_SKIPPED:
9323                    numberOfPackagesSkipped++;
9324                    break;
9325                case PackageDexOptimizer.DEX_OPT_FAILED:
9326                    numberOfPackagesFailed++;
9327                    break;
9328                default:
9329                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
9330                    break;
9331            }
9332        }
9333
9334        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
9335                numberOfPackagesFailed };
9336    }
9337
9338    @Override
9339    public void notifyPackageUse(String packageName, int reason) {
9340        synchronized (mPackages) {
9341            final int callingUid = Binder.getCallingUid();
9342            final int callingUserId = UserHandle.getUserId(callingUid);
9343            if (getInstantAppPackageName(callingUid) != null) {
9344                if (!isCallerSameApp(packageName, callingUid)) {
9345                    return;
9346                }
9347            } else {
9348                if (isInstantApp(packageName, callingUserId)) {
9349                    return;
9350                }
9351            }
9352            final PackageParser.Package p = mPackages.get(packageName);
9353            if (p == null) {
9354                return;
9355            }
9356            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9357        }
9358    }
9359
9360    @Override
9361    public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) {
9362        int userId = UserHandle.getCallingUserId();
9363        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9364        if (ai == null) {
9365            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9366                + loadingPackageName + ", user=" + userId);
9367            return;
9368        }
9369        mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId);
9370    }
9371
9372    @Override
9373    public boolean performDexOpt(String packageName,
9374            boolean checkProfiles, int compileReason, boolean force, boolean bootComplete) {
9375        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9376            return false;
9377        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9378            return false;
9379        }
9380        int dexoptStatus = performDexOptWithStatus(
9381              packageName, checkProfiles, compileReason, force, bootComplete);
9382        return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9383    }
9384
9385    /**
9386     * Perform dexopt on the given package and return one of following result:
9387     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9388     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9389     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
9390     */
9391    /* package */ int performDexOptWithStatus(String packageName,
9392            boolean checkProfiles, int compileReason, boolean force, boolean bootComplete) {
9393        return performDexOptTraced(packageName, checkProfiles,
9394                getCompilerFilterForReason(compileReason), force, bootComplete);
9395    }
9396
9397    @Override
9398    public boolean performDexOptMode(String packageName,
9399            boolean checkProfiles, String targetCompilerFilter, boolean force,
9400            boolean bootComplete) {
9401        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9402            return false;
9403        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9404            return false;
9405        }
9406        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
9407                targetCompilerFilter, force, bootComplete);
9408        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9409    }
9410
9411    private int performDexOptTraced(String packageName,
9412                boolean checkProfiles, String targetCompilerFilter, boolean force,
9413                boolean bootComplete) {
9414        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9415        try {
9416            return performDexOptInternal(packageName, checkProfiles,
9417                    targetCompilerFilter, force, bootComplete);
9418        } finally {
9419            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9420        }
9421    }
9422
9423    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
9424    // if the package can now be considered up to date for the given filter.
9425    private int performDexOptInternal(String packageName,
9426                boolean checkProfiles, String targetCompilerFilter, boolean force,
9427                boolean bootComplete) {
9428        PackageParser.Package p;
9429        synchronized (mPackages) {
9430            p = mPackages.get(packageName);
9431            if (p == null) {
9432                // Package could not be found. Report failure.
9433                return PackageDexOptimizer.DEX_OPT_FAILED;
9434            }
9435            mPackageUsage.maybeWriteAsync(mPackages);
9436            mCompilerStats.maybeWriteAsync();
9437        }
9438        long callingId = Binder.clearCallingIdentity();
9439        try {
9440            synchronized (mInstallLock) {
9441                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
9442                        targetCompilerFilter, force, bootComplete);
9443            }
9444        } finally {
9445            Binder.restoreCallingIdentity(callingId);
9446        }
9447    }
9448
9449    public ArraySet<String> getOptimizablePackages() {
9450        ArraySet<String> pkgs = new ArraySet<String>();
9451        synchronized (mPackages) {
9452            for (PackageParser.Package p : mPackages.values()) {
9453                if (PackageDexOptimizer.canOptimizePackage(p)) {
9454                    pkgs.add(p.packageName);
9455                }
9456            }
9457        }
9458        return pkgs;
9459    }
9460
9461    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
9462            boolean checkProfiles, String targetCompilerFilter,
9463            boolean force, boolean bootComplete) {
9464        // Select the dex optimizer based on the force parameter.
9465        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
9466        //       allocate an object here.
9467        PackageDexOptimizer pdo = force
9468                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
9469                : mPackageDexOptimizer;
9470
9471        // Dexopt all dependencies first. Note: we ignore the return value and march on
9472        // on errors.
9473        // Note that we are going to call performDexOpt on those libraries as many times as
9474        // they are referenced in packages. When we do a batch of performDexOpt (for example
9475        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
9476        // and the first package that uses the library will dexopt it. The
9477        // others will see that the compiled code for the library is up to date.
9478        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
9479        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
9480        if (!deps.isEmpty()) {
9481            for (PackageParser.Package depPackage : deps) {
9482                // TODO: Analyze and investigate if we (should) profile libraries.
9483                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
9484                        false /* checkProfiles */,
9485                        targetCompilerFilter,
9486                        getOrCreateCompilerPackageStats(depPackage),
9487                        true /* isUsedByOtherApps */,
9488                        bootComplete);
9489            }
9490        }
9491        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
9492                targetCompilerFilter, getOrCreateCompilerPackageStats(p),
9493                mDexManager.isUsedByOtherApps(p.packageName), bootComplete);
9494    }
9495
9496    // Performs dexopt on the used secondary dex files belonging to the given package.
9497    // Returns true if all dex files were process successfully (which could mean either dexopt or
9498    // skip). Returns false if any of the files caused errors.
9499    @Override
9500    public boolean performDexOptSecondary(String packageName, String compilerFilter,
9501            boolean force) {
9502        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9503            return false;
9504        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9505            return false;
9506        }
9507        mDexManager.reconcileSecondaryDexFiles(packageName);
9508        return mDexManager.dexoptSecondaryDex(packageName, compilerFilter, force);
9509    }
9510
9511    public boolean performDexOptSecondary(String packageName, int compileReason,
9512            boolean force) {
9513        return mDexManager.dexoptSecondaryDex(packageName, compileReason, force);
9514    }
9515
9516    /**
9517     * Reconcile the information we have about the secondary dex files belonging to
9518     * {@code packagName} and the actual dex files. For all dex files that were
9519     * deleted, update the internal records and delete the generated oat files.
9520     */
9521    @Override
9522    public void reconcileSecondaryDexFiles(String packageName) {
9523        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9524            return;
9525        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9526            return;
9527        }
9528        mDexManager.reconcileSecondaryDexFiles(packageName);
9529    }
9530
9531    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
9532    // a reference there.
9533    /*package*/ DexManager getDexManager() {
9534        return mDexManager;
9535    }
9536
9537    /**
9538     * Execute the background dexopt job immediately.
9539     */
9540    @Override
9541    public boolean runBackgroundDexoptJob() {
9542        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9543            return false;
9544        }
9545        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
9546    }
9547
9548    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
9549        if (p.usesLibraries != null || p.usesOptionalLibraries != null
9550                || p.usesStaticLibraries != null) {
9551            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
9552            Set<String> collectedNames = new HashSet<>();
9553            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
9554
9555            retValue.remove(p);
9556
9557            return retValue;
9558        } else {
9559            return Collections.emptyList();
9560        }
9561    }
9562
9563    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
9564            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9565        if (!collectedNames.contains(p.packageName)) {
9566            collectedNames.add(p.packageName);
9567            collected.add(p);
9568
9569            if (p.usesLibraries != null) {
9570                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
9571                        null, collected, collectedNames);
9572            }
9573            if (p.usesOptionalLibraries != null) {
9574                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
9575                        null, collected, collectedNames);
9576            }
9577            if (p.usesStaticLibraries != null) {
9578                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
9579                        p.usesStaticLibrariesVersions, collected, collectedNames);
9580            }
9581        }
9582    }
9583
9584    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
9585            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9586        final int libNameCount = libs.size();
9587        for (int i = 0; i < libNameCount; i++) {
9588            String libName = libs.get(i);
9589            int version = (versions != null && versions.length == libNameCount)
9590                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
9591            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
9592            if (libPkg != null) {
9593                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
9594            }
9595        }
9596    }
9597
9598    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
9599        synchronized (mPackages) {
9600            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
9601            if (libEntry != null) {
9602                return mPackages.get(libEntry.apk);
9603            }
9604            return null;
9605        }
9606    }
9607
9608    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
9609        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9610        if (versionedLib == null) {
9611            return null;
9612        }
9613        return versionedLib.get(version);
9614    }
9615
9616    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
9617        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9618                pkg.staticSharedLibName);
9619        if (versionedLib == null) {
9620            return null;
9621        }
9622        int previousLibVersion = -1;
9623        final int versionCount = versionedLib.size();
9624        for (int i = 0; i < versionCount; i++) {
9625            final int libVersion = versionedLib.keyAt(i);
9626            if (libVersion < pkg.staticSharedLibVersion) {
9627                previousLibVersion = Math.max(previousLibVersion, libVersion);
9628            }
9629        }
9630        if (previousLibVersion >= 0) {
9631            return versionedLib.get(previousLibVersion);
9632        }
9633        return null;
9634    }
9635
9636    public void shutdown() {
9637        mPackageUsage.writeNow(mPackages);
9638        mCompilerStats.writeNow();
9639    }
9640
9641    @Override
9642    public void dumpProfiles(String packageName) {
9643        PackageParser.Package pkg;
9644        synchronized (mPackages) {
9645            pkg = mPackages.get(packageName);
9646            if (pkg == null) {
9647                throw new IllegalArgumentException("Unknown package: " + packageName);
9648            }
9649        }
9650        /* Only the shell, root, or the app user should be able to dump profiles. */
9651        int callingUid = Binder.getCallingUid();
9652        if (callingUid != Process.SHELL_UID &&
9653            callingUid != Process.ROOT_UID &&
9654            callingUid != pkg.applicationInfo.uid) {
9655            throw new SecurityException("dumpProfiles");
9656        }
9657
9658        synchronized (mInstallLock) {
9659            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
9660            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
9661            try {
9662                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
9663                String codePaths = TextUtils.join(";", allCodePaths);
9664                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
9665            } catch (InstallerException e) {
9666                Slog.w(TAG, "Failed to dump profiles", e);
9667            }
9668            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9669        }
9670    }
9671
9672    @Override
9673    public void forceDexOpt(String packageName) {
9674        enforceSystemOrRoot("forceDexOpt");
9675
9676        PackageParser.Package pkg;
9677        synchronized (mPackages) {
9678            pkg = mPackages.get(packageName);
9679            if (pkg == null) {
9680                throw new IllegalArgumentException("Unknown package: " + packageName);
9681            }
9682        }
9683
9684        synchronized (mInstallLock) {
9685            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9686
9687            // Whoever is calling forceDexOpt wants a compiled package.
9688            // Don't use profiles since that may cause compilation to be skipped.
9689            final int res = performDexOptInternalWithDependenciesLI(pkg,
9690                    false /* checkProfiles */, getDefaultCompilerFilter(),
9691                    true /* force */,
9692                    true /* bootComplete */);
9693
9694            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9695            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
9696                throw new IllegalStateException("Failed to dexopt: " + res);
9697            }
9698        }
9699    }
9700
9701    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
9702        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
9703            Slog.w(TAG, "Unable to update from " + oldPkg.name
9704                    + " to " + newPkg.packageName
9705                    + ": old package not in system partition");
9706            return false;
9707        } else if (mPackages.get(oldPkg.name) != null) {
9708            Slog.w(TAG, "Unable to update from " + oldPkg.name
9709                    + " to " + newPkg.packageName
9710                    + ": old package still exists");
9711            return false;
9712        }
9713        return true;
9714    }
9715
9716    void removeCodePathLI(File codePath) {
9717        if (codePath.isDirectory()) {
9718            try {
9719                mInstaller.rmPackageDir(codePath.getAbsolutePath());
9720            } catch (InstallerException e) {
9721                Slog.w(TAG, "Failed to remove code path", e);
9722            }
9723        } else {
9724            codePath.delete();
9725        }
9726    }
9727
9728    private int[] resolveUserIds(int userId) {
9729        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
9730    }
9731
9732    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9733        if (pkg == null) {
9734            Slog.wtf(TAG, "Package was null!", new Throwable());
9735            return;
9736        }
9737        clearAppDataLeafLIF(pkg, userId, flags);
9738        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9739        for (int i = 0; i < childCount; i++) {
9740            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9741        }
9742    }
9743
9744    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9745        final PackageSetting ps;
9746        synchronized (mPackages) {
9747            ps = mSettings.mPackages.get(pkg.packageName);
9748        }
9749        for (int realUserId : resolveUserIds(userId)) {
9750            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9751            try {
9752                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9753                        ceDataInode);
9754            } catch (InstallerException e) {
9755                Slog.w(TAG, String.valueOf(e));
9756            }
9757        }
9758    }
9759
9760    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9761        if (pkg == null) {
9762            Slog.wtf(TAG, "Package was null!", new Throwable());
9763            return;
9764        }
9765        destroyAppDataLeafLIF(pkg, userId, flags);
9766        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9767        for (int i = 0; i < childCount; i++) {
9768            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9769        }
9770    }
9771
9772    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9773        final PackageSetting ps;
9774        synchronized (mPackages) {
9775            ps = mSettings.mPackages.get(pkg.packageName);
9776        }
9777        for (int realUserId : resolveUserIds(userId)) {
9778            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9779            try {
9780                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9781                        ceDataInode);
9782            } catch (InstallerException e) {
9783                Slog.w(TAG, String.valueOf(e));
9784            }
9785            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
9786        }
9787    }
9788
9789    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
9790        if (pkg == null) {
9791            Slog.wtf(TAG, "Package was null!", new Throwable());
9792            return;
9793        }
9794        destroyAppProfilesLeafLIF(pkg);
9795        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9796        for (int i = 0; i < childCount; i++) {
9797            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
9798        }
9799    }
9800
9801    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
9802        try {
9803            mInstaller.destroyAppProfiles(pkg.packageName);
9804        } catch (InstallerException e) {
9805            Slog.w(TAG, String.valueOf(e));
9806        }
9807    }
9808
9809    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
9810        if (pkg == null) {
9811            Slog.wtf(TAG, "Package was null!", new Throwable());
9812            return;
9813        }
9814        clearAppProfilesLeafLIF(pkg);
9815        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9816        for (int i = 0; i < childCount; i++) {
9817            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
9818        }
9819    }
9820
9821    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
9822        try {
9823            mInstaller.clearAppProfiles(pkg.packageName);
9824        } catch (InstallerException e) {
9825            Slog.w(TAG, String.valueOf(e));
9826        }
9827    }
9828
9829    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
9830            long lastUpdateTime) {
9831        // Set parent install/update time
9832        PackageSetting ps = (PackageSetting) pkg.mExtras;
9833        if (ps != null) {
9834            ps.firstInstallTime = firstInstallTime;
9835            ps.lastUpdateTime = lastUpdateTime;
9836        }
9837        // Set children install/update time
9838        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9839        for (int i = 0; i < childCount; i++) {
9840            PackageParser.Package childPkg = pkg.childPackages.get(i);
9841            ps = (PackageSetting) childPkg.mExtras;
9842            if (ps != null) {
9843                ps.firstInstallTime = firstInstallTime;
9844                ps.lastUpdateTime = lastUpdateTime;
9845            }
9846        }
9847    }
9848
9849    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
9850            PackageParser.Package changingLib) {
9851        if (file.path != null) {
9852            usesLibraryFiles.add(file.path);
9853            return;
9854        }
9855        PackageParser.Package p = mPackages.get(file.apk);
9856        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
9857            // If we are doing this while in the middle of updating a library apk,
9858            // then we need to make sure to use that new apk for determining the
9859            // dependencies here.  (We haven't yet finished committing the new apk
9860            // to the package manager state.)
9861            if (p == null || p.packageName.equals(changingLib.packageName)) {
9862                p = changingLib;
9863            }
9864        }
9865        if (p != null) {
9866            usesLibraryFiles.addAll(p.getAllCodePaths());
9867            if (p.usesLibraryFiles != null) {
9868                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
9869            }
9870        }
9871    }
9872
9873    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
9874            PackageParser.Package changingLib) throws PackageManagerException {
9875        if (pkg == null) {
9876            return;
9877        }
9878        ArraySet<String> usesLibraryFiles = null;
9879        if (pkg.usesLibraries != null) {
9880            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
9881                    null, null, pkg.packageName, changingLib, true, null);
9882        }
9883        if (pkg.usesStaticLibraries != null) {
9884            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
9885                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
9886                    pkg.packageName, changingLib, true, usesLibraryFiles);
9887        }
9888        if (pkg.usesOptionalLibraries != null) {
9889            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
9890                    null, null, pkg.packageName, changingLib, false, usesLibraryFiles);
9891        }
9892        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
9893            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
9894        } else {
9895            pkg.usesLibraryFiles = null;
9896        }
9897    }
9898
9899    private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
9900            @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests,
9901            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
9902            boolean required, @Nullable ArraySet<String> outUsedLibraries)
9903            throws PackageManagerException {
9904        final int libCount = requestedLibraries.size();
9905        for (int i = 0; i < libCount; i++) {
9906            final String libName = requestedLibraries.get(i);
9907            final int libVersion = requiredVersions != null ? requiredVersions[i]
9908                    : SharedLibraryInfo.VERSION_UNDEFINED;
9909            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
9910            if (libEntry == null) {
9911                if (required) {
9912                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9913                            "Package " + packageName + " requires unavailable shared library "
9914                                    + libName + "; failing!");
9915                } else if (DEBUG_SHARED_LIBRARIES) {
9916                    Slog.i(TAG, "Package " + packageName
9917                            + " desires unavailable shared library "
9918                            + libName + "; ignoring!");
9919                }
9920            } else {
9921                if (requiredVersions != null && requiredCertDigests != null) {
9922                    if (libEntry.info.getVersion() != requiredVersions[i]) {
9923                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9924                            "Package " + packageName + " requires unavailable static shared"
9925                                    + " library " + libName + " version "
9926                                    + libEntry.info.getVersion() + "; failing!");
9927                    }
9928
9929                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
9930                    if (libPkg == null) {
9931                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9932                                "Package " + packageName + " requires unavailable static shared"
9933                                        + " library; failing!");
9934                    }
9935
9936                    String expectedCertDigest = requiredCertDigests[i];
9937                    String libCertDigest = PackageUtils.computeCertSha256Digest(
9938                                libPkg.mSignatures[0]);
9939                    if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) {
9940                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9941                                "Package " + packageName + " requires differently signed" +
9942                                        " static shared library; failing!");
9943                    }
9944                }
9945
9946                if (outUsedLibraries == null) {
9947                    outUsedLibraries = new ArraySet<>();
9948                }
9949                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
9950            }
9951        }
9952        return outUsedLibraries;
9953    }
9954
9955    private static boolean hasString(List<String> list, List<String> which) {
9956        if (list == null) {
9957            return false;
9958        }
9959        for (int i=list.size()-1; i>=0; i--) {
9960            for (int j=which.size()-1; j>=0; j--) {
9961                if (which.get(j).equals(list.get(i))) {
9962                    return true;
9963                }
9964            }
9965        }
9966        return false;
9967    }
9968
9969    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
9970            PackageParser.Package changingPkg) {
9971        ArrayList<PackageParser.Package> res = null;
9972        for (PackageParser.Package pkg : mPackages.values()) {
9973            if (changingPkg != null
9974                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
9975                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
9976                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
9977                            changingPkg.staticSharedLibName)) {
9978                return null;
9979            }
9980            if (res == null) {
9981                res = new ArrayList<>();
9982            }
9983            res.add(pkg);
9984            try {
9985                updateSharedLibrariesLPr(pkg, changingPkg);
9986            } catch (PackageManagerException e) {
9987                // If a system app update or an app and a required lib missing we
9988                // delete the package and for updated system apps keep the data as
9989                // it is better for the user to reinstall than to be in an limbo
9990                // state. Also libs disappearing under an app should never happen
9991                // - just in case.
9992                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
9993                    final int flags = pkg.isUpdatedSystemApp()
9994                            ? PackageManager.DELETE_KEEP_DATA : 0;
9995                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
9996                            flags , null, true, null);
9997                }
9998                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
9999            }
10000        }
10001        return res;
10002    }
10003
10004    /**
10005     * Derive the value of the {@code cpuAbiOverride} based on the provided
10006     * value and an optional stored value from the package settings.
10007     */
10008    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
10009        String cpuAbiOverride = null;
10010
10011        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
10012            cpuAbiOverride = null;
10013        } else if (abiOverride != null) {
10014            cpuAbiOverride = abiOverride;
10015        } else if (settings != null) {
10016            cpuAbiOverride = settings.cpuAbiOverrideString;
10017        }
10018
10019        return cpuAbiOverride;
10020    }
10021
10022    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
10023            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
10024                    throws PackageManagerException {
10025        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
10026        // If the package has children and this is the first dive in the function
10027        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
10028        // whether all packages (parent and children) would be successfully scanned
10029        // before the actual scan since scanning mutates internal state and we want
10030        // to atomically install the package and its children.
10031        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10032            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
10033                scanFlags |= SCAN_CHECK_ONLY;
10034            }
10035        } else {
10036            scanFlags &= ~SCAN_CHECK_ONLY;
10037        }
10038
10039        final PackageParser.Package scannedPkg;
10040        try {
10041            // Scan the parent
10042            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
10043            // Scan the children
10044            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10045            for (int i = 0; i < childCount; i++) {
10046                PackageParser.Package childPkg = pkg.childPackages.get(i);
10047                scanPackageLI(childPkg, policyFlags,
10048                        scanFlags, currentTime, user);
10049            }
10050        } finally {
10051            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10052        }
10053
10054        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10055            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
10056        }
10057
10058        return scannedPkg;
10059    }
10060
10061    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
10062            int scanFlags, long currentTime, @Nullable UserHandle user)
10063                    throws PackageManagerException {
10064        boolean success = false;
10065        try {
10066            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
10067                    currentTime, user);
10068            success = true;
10069            return res;
10070        } finally {
10071            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
10072                // DELETE_DATA_ON_FAILURES is only used by frozen paths
10073                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
10074                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
10075                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
10076            }
10077        }
10078    }
10079
10080    /**
10081     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
10082     */
10083    private static boolean apkHasCode(String fileName) {
10084        StrictJarFile jarFile = null;
10085        try {
10086            jarFile = new StrictJarFile(fileName,
10087                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
10088            return jarFile.findEntry("classes.dex") != null;
10089        } catch (IOException ignore) {
10090        } finally {
10091            try {
10092                if (jarFile != null) {
10093                    jarFile.close();
10094                }
10095            } catch (IOException ignore) {}
10096        }
10097        return false;
10098    }
10099
10100    /**
10101     * Enforces code policy for the package. This ensures that if an APK has
10102     * declared hasCode="true" in its manifest that the APK actually contains
10103     * code.
10104     *
10105     * @throws PackageManagerException If bytecode could not be found when it should exist
10106     */
10107    private static void assertCodePolicy(PackageParser.Package pkg)
10108            throws PackageManagerException {
10109        final boolean shouldHaveCode =
10110                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10111        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10112            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10113                    "Package " + pkg.baseCodePath + " code is missing");
10114        }
10115
10116        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10117            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10118                final boolean splitShouldHaveCode =
10119                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10120                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10121                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10122                            "Package " + pkg.splitCodePaths[i] + " code is missing");
10123                }
10124            }
10125        }
10126    }
10127
10128    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
10129            final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
10130                    throws PackageManagerException {
10131        if (DEBUG_PACKAGE_SCANNING) {
10132            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10133                Log.d(TAG, "Scanning package " + pkg.packageName);
10134        }
10135
10136        applyPolicy(pkg, policyFlags);
10137
10138        assertPackageIsValid(pkg, policyFlags, scanFlags);
10139
10140        if (Build.IS_DEBUGGABLE &&
10141                pkg.isPrivilegedApp() &&
10142                !SystemProperties.getBoolean("pm.dexopt.priv-apps", true)) {
10143            PackageManagerServiceUtils.logPackageHasUncompressedCode(pkg);
10144        }
10145
10146        // Initialize package source and resource directories
10147        final File scanFile = new File(pkg.codePath);
10148        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10149        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10150
10151        SharedUserSetting suid = null;
10152        PackageSetting pkgSetting = null;
10153
10154        // Getting the package setting may have a side-effect, so if we
10155        // are only checking if scan would succeed, stash a copy of the
10156        // old setting to restore at the end.
10157        PackageSetting nonMutatedPs = null;
10158
10159        // We keep references to the derived CPU Abis from settings in oder to reuse
10160        // them in the case where we're not upgrading or booting for the first time.
10161        String primaryCpuAbiFromSettings = null;
10162        String secondaryCpuAbiFromSettings = null;
10163        boolean needToDeriveAbi = (scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0;
10164
10165        // writer
10166        synchronized (mPackages) {
10167            if (pkg.mSharedUserId != null) {
10168                // SIDE EFFECTS; may potentially allocate a new shared user
10169                suid = mSettings.getSharedUserLPw(
10170                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
10171                if (DEBUG_PACKAGE_SCANNING) {
10172                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10173                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
10174                                + "): packages=" + suid.packages);
10175                }
10176            }
10177
10178            // Check if we are renaming from an original package name.
10179            PackageSetting origPackage = null;
10180            String realName = null;
10181            if (pkg.mOriginalPackages != null) {
10182                // This package may need to be renamed to a previously
10183                // installed name.  Let's check on that...
10184                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
10185                if (pkg.mOriginalPackages.contains(renamed)) {
10186                    // This package had originally been installed as the
10187                    // original name, and we have already taken care of
10188                    // transitioning to the new one.  Just update the new
10189                    // one to continue using the old name.
10190                    realName = pkg.mRealPackage;
10191                    if (!pkg.packageName.equals(renamed)) {
10192                        // Callers into this function may have already taken
10193                        // care of renaming the package; only do it here if
10194                        // it is not already done.
10195                        pkg.setPackageName(renamed);
10196                    }
10197                } else {
10198                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
10199                        if ((origPackage = mSettings.getPackageLPr(
10200                                pkg.mOriginalPackages.get(i))) != null) {
10201                            // We do have the package already installed under its
10202                            // original name...  should we use it?
10203                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
10204                                // New package is not compatible with original.
10205                                origPackage = null;
10206                                continue;
10207                            } else if (origPackage.sharedUser != null) {
10208                                // Make sure uid is compatible between packages.
10209                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
10210                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
10211                                            + " to " + pkg.packageName + ": old uid "
10212                                            + origPackage.sharedUser.name
10213                                            + " differs from " + pkg.mSharedUserId);
10214                                    origPackage = null;
10215                                    continue;
10216                                }
10217                                // TODO: Add case when shared user id is added [b/28144775]
10218                            } else {
10219                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10220                                        + pkg.packageName + " to old name " + origPackage.name);
10221                            }
10222                            break;
10223                        }
10224                    }
10225                }
10226            }
10227
10228            if (mTransferedPackages.contains(pkg.packageName)) {
10229                Slog.w(TAG, "Package " + pkg.packageName
10230                        + " was transferred to another, but its .apk remains");
10231            }
10232
10233            // See comments in nonMutatedPs declaration
10234            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10235                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10236                if (foundPs != null) {
10237                    nonMutatedPs = new PackageSetting(foundPs);
10238                }
10239            }
10240
10241            if (!needToDeriveAbi) {
10242                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10243                if (foundPs != null) {
10244                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
10245                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
10246                } else {
10247                    // when re-adding a system package failed after uninstalling updates.
10248                    needToDeriveAbi = true;
10249                }
10250            }
10251
10252            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
10253            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
10254                PackageManagerService.reportSettingsProblem(Log.WARN,
10255                        "Package " + pkg.packageName + " shared user changed from "
10256                                + (pkgSetting.sharedUser != null
10257                                        ? pkgSetting.sharedUser.name : "<nothing>")
10258                                + " to "
10259                                + (suid != null ? suid.name : "<nothing>")
10260                                + "; replacing with new");
10261                pkgSetting = null;
10262            }
10263            final PackageSetting oldPkgSetting =
10264                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
10265            final PackageSetting disabledPkgSetting =
10266                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
10267
10268            String[] usesStaticLibraries = null;
10269            if (pkg.usesStaticLibraries != null) {
10270                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10271                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10272            }
10273
10274            if (pkgSetting == null) {
10275                final String parentPackageName = (pkg.parentPackage != null)
10276                        ? pkg.parentPackage.packageName : null;
10277                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10278                // REMOVE SharedUserSetting from method; update in a separate call
10279                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
10280                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
10281                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
10282                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
10283                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
10284                        true /*allowInstall*/, instantApp, parentPackageName,
10285                        pkg.getChildPackageNames(), UserManagerService.getInstance(),
10286                        usesStaticLibraries, pkg.usesStaticLibrariesVersions);
10287                // SIDE EFFECTS; updates system state; move elsewhere
10288                if (origPackage != null) {
10289                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
10290                }
10291                mSettings.addUserToSettingLPw(pkgSetting);
10292            } else {
10293                // REMOVE SharedUserSetting from method; update in a separate call.
10294                //
10295                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10296                // secondaryCpuAbi are not known at this point so we always update them
10297                // to null here, only to reset them at a later point.
10298                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
10299                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
10300                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
10301                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
10302                        UserManagerService.getInstance(), usesStaticLibraries,
10303                        pkg.usesStaticLibrariesVersions);
10304            }
10305            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
10306            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10307
10308            // SIDE EFFECTS; modifies system state; move elsewhere
10309            if (pkgSetting.origPackage != null) {
10310                // If we are first transitioning from an original package,
10311                // fix up the new package's name now.  We need to do this after
10312                // looking up the package under its new name, so getPackageLP
10313                // can take care of fiddling things correctly.
10314                pkg.setPackageName(origPackage.name);
10315
10316                // File a report about this.
10317                String msg = "New package " + pkgSetting.realName
10318                        + " renamed to replace old package " + pkgSetting.name;
10319                reportSettingsProblem(Log.WARN, msg);
10320
10321                // Make a note of it.
10322                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10323                    mTransferedPackages.add(origPackage.name);
10324                }
10325
10326                // No longer need to retain this.
10327                pkgSetting.origPackage = null;
10328            }
10329
10330            // SIDE EFFECTS; modifies system state; move elsewhere
10331            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
10332                // Make a note of it.
10333                mTransferedPackages.add(pkg.packageName);
10334            }
10335
10336            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
10337                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10338            }
10339
10340            if ((scanFlags & SCAN_BOOTING) == 0
10341                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10342                // Check all shared libraries and map to their actual file path.
10343                // We only do this here for apps not on a system dir, because those
10344                // are the only ones that can fail an install due to this.  We
10345                // will take care of the system apps by updating all of their
10346                // library paths after the scan is done. Also during the initial
10347                // scan don't update any libs as we do this wholesale after all
10348                // apps are scanned to avoid dependency based scanning.
10349                updateSharedLibrariesLPr(pkg, null);
10350            }
10351
10352            if (mFoundPolicyFile) {
10353                SELinuxMMAC.assignSeInfoValue(pkg);
10354            }
10355            pkg.applicationInfo.uid = pkgSetting.appId;
10356            pkg.mExtras = pkgSetting;
10357
10358
10359            // Static shared libs have same package with different versions where
10360            // we internally use a synthetic package name to allow multiple versions
10361            // of the same package, therefore we need to compare signatures against
10362            // the package setting for the latest library version.
10363            PackageSetting signatureCheckPs = pkgSetting;
10364            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10365                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10366                if (libraryEntry != null) {
10367                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10368                }
10369            }
10370
10371            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
10372                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
10373                    // We just determined the app is signed correctly, so bring
10374                    // over the latest parsed certs.
10375                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10376                } else {
10377                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10378                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10379                                "Package " + pkg.packageName + " upgrade keys do not match the "
10380                                + "previously installed version");
10381                    } else {
10382                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
10383                        String msg = "System package " + pkg.packageName
10384                                + " signature changed; retaining data.";
10385                        reportSettingsProblem(Log.WARN, msg);
10386                    }
10387                }
10388            } else {
10389                try {
10390                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
10391                    verifySignaturesLP(signatureCheckPs, pkg);
10392                    // We just determined the app is signed correctly, so bring
10393                    // over the latest parsed certs.
10394                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10395                } catch (PackageManagerException e) {
10396                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10397                        throw e;
10398                    }
10399                    // The signature has changed, but this package is in the system
10400                    // image...  let's recover!
10401                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10402                    // However...  if this package is part of a shared user, but it
10403                    // doesn't match the signature of the shared user, let's fail.
10404                    // What this means is that you can't change the signatures
10405                    // associated with an overall shared user, which doesn't seem all
10406                    // that unreasonable.
10407                    if (signatureCheckPs.sharedUser != null) {
10408                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
10409                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
10410                            throw new PackageManagerException(
10411                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10412                                    "Signature mismatch for shared user: "
10413                                            + pkgSetting.sharedUser);
10414                        }
10415                    }
10416                    // File a report about this.
10417                    String msg = "System package " + pkg.packageName
10418                            + " signature changed; retaining data.";
10419                    reportSettingsProblem(Log.WARN, msg);
10420                }
10421            }
10422
10423            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
10424                // This package wants to adopt ownership of permissions from
10425                // another package.
10426                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
10427                    final String origName = pkg.mAdoptPermissions.get(i);
10428                    final PackageSetting orig = mSettings.getPackageLPr(origName);
10429                    if (orig != null) {
10430                        if (verifyPackageUpdateLPr(orig, pkg)) {
10431                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
10432                                    + pkg.packageName);
10433                            // SIDE EFFECTS; updates permissions system state; move elsewhere
10434                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
10435                        }
10436                    }
10437                }
10438            }
10439        }
10440
10441        pkg.applicationInfo.processName = fixProcessName(
10442                pkg.applicationInfo.packageName,
10443                pkg.applicationInfo.processName);
10444
10445        if (pkg != mPlatformPackage) {
10446            // Get all of our default paths setup
10447            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10448        }
10449
10450        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10451
10452        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10453            if (needToDeriveAbi) {
10454                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10455                final boolean extractNativeLibs = !pkg.isLibrary();
10456                derivePackageAbi(pkg, scanFile, cpuAbiOverride, extractNativeLibs,
10457                        mAppLib32InstallDir);
10458                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10459
10460                // Some system apps still use directory structure for native libraries
10461                // in which case we might end up not detecting abi solely based on apk
10462                // structure. Try to detect abi based on directory structure.
10463                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
10464                        pkg.applicationInfo.primaryCpuAbi == null) {
10465                    setBundledAppAbisAndRoots(pkg, pkgSetting);
10466                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10467                }
10468            } else {
10469                // This is not a first boot or an upgrade, don't bother deriving the
10470                // ABI during the scan. Instead, trust the value that was stored in the
10471                // package setting.
10472                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
10473                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
10474
10475                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10476
10477                if (DEBUG_ABI_SELECTION) {
10478                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
10479                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
10480                        pkg.applicationInfo.secondaryCpuAbi);
10481                }
10482            }
10483        } else {
10484            if ((scanFlags & SCAN_MOVE) != 0) {
10485                // We haven't run dex-opt for this move (since we've moved the compiled output too)
10486                // but we already have this packages package info in the PackageSetting. We just
10487                // use that and derive the native library path based on the new codepath.
10488                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
10489                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
10490            }
10491
10492            // Set native library paths again. For moves, the path will be updated based on the
10493            // ABIs we've determined above. For non-moves, the path will be updated based on the
10494            // ABIs we determined during compilation, but the path will depend on the final
10495            // package path (after the rename away from the stage path).
10496            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10497        }
10498
10499        // This is a special case for the "system" package, where the ABI is
10500        // dictated by the zygote configuration (and init.rc). We should keep track
10501        // of this ABI so that we can deal with "normal" applications that run under
10502        // the same UID correctly.
10503        if (mPlatformPackage == pkg) {
10504            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
10505                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
10506        }
10507
10508        // If there's a mismatch between the abi-override in the package setting
10509        // and the abiOverride specified for the install. Warn about this because we
10510        // would've already compiled the app without taking the package setting into
10511        // account.
10512        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
10513            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
10514                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
10515                        " for package " + pkg.packageName);
10516            }
10517        }
10518
10519        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10520        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10521        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
10522
10523        // Copy the derived override back to the parsed package, so that we can
10524        // update the package settings accordingly.
10525        pkg.cpuAbiOverride = cpuAbiOverride;
10526
10527        if (DEBUG_ABI_SELECTION) {
10528            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
10529                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
10530                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
10531        }
10532
10533        // Push the derived path down into PackageSettings so we know what to
10534        // clean up at uninstall time.
10535        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
10536
10537        if (DEBUG_ABI_SELECTION) {
10538            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
10539                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
10540                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
10541        }
10542
10543        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
10544        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
10545            // We don't do this here during boot because we can do it all
10546            // at once after scanning all existing packages.
10547            //
10548            // We also do this *before* we perform dexopt on this package, so that
10549            // we can avoid redundant dexopts, and also to make sure we've got the
10550            // code and package path correct.
10551            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
10552        }
10553
10554        if (mFactoryTest && pkg.requestedPermissions.contains(
10555                android.Manifest.permission.FACTORY_TEST)) {
10556            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
10557        }
10558
10559        if (isSystemApp(pkg)) {
10560            pkgSetting.isOrphaned = true;
10561        }
10562
10563        // Take care of first install / last update times.
10564        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
10565        if (currentTime != 0) {
10566            if (pkgSetting.firstInstallTime == 0) {
10567                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
10568            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
10569                pkgSetting.lastUpdateTime = currentTime;
10570            }
10571        } else if (pkgSetting.firstInstallTime == 0) {
10572            // We need *something*.  Take time time stamp of the file.
10573            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
10574        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
10575            if (scanFileTime != pkgSetting.timeStamp) {
10576                // A package on the system image has changed; consider this
10577                // to be an update.
10578                pkgSetting.lastUpdateTime = scanFileTime;
10579            }
10580        }
10581        pkgSetting.setTimeStamp(scanFileTime);
10582
10583        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10584            if (nonMutatedPs != null) {
10585                synchronized (mPackages) {
10586                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
10587                }
10588            }
10589        } else {
10590            final int userId = user == null ? 0 : user.getIdentifier();
10591            // Modify state for the given package setting
10592            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
10593                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
10594            if (pkgSetting.getInstantApp(userId)) {
10595                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
10596            }
10597        }
10598        return pkg;
10599    }
10600
10601    /**
10602     * Applies policy to the parsed package based upon the given policy flags.
10603     * Ensures the package is in a good state.
10604     * <p>
10605     * Implementation detail: This method must NOT have any side effect. It would
10606     * ideally be static, but, it requires locks to read system state.
10607     */
10608    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
10609        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
10610            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
10611            if (pkg.applicationInfo.isDirectBootAware()) {
10612                // we're direct boot aware; set for all components
10613                for (PackageParser.Service s : pkg.services) {
10614                    s.info.encryptionAware = s.info.directBootAware = true;
10615                }
10616                for (PackageParser.Provider p : pkg.providers) {
10617                    p.info.encryptionAware = p.info.directBootAware = true;
10618                }
10619                for (PackageParser.Activity a : pkg.activities) {
10620                    a.info.encryptionAware = a.info.directBootAware = true;
10621                }
10622                for (PackageParser.Activity r : pkg.receivers) {
10623                    r.info.encryptionAware = r.info.directBootAware = true;
10624                }
10625            }
10626        } else {
10627            // Only allow system apps to be flagged as core apps.
10628            pkg.coreApp = false;
10629            // clear flags not applicable to regular apps
10630            pkg.applicationInfo.privateFlags &=
10631                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
10632            pkg.applicationInfo.privateFlags &=
10633                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
10634        }
10635        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
10636
10637        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
10638            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
10639        }
10640
10641        if (!isSystemApp(pkg)) {
10642            // Only system apps can use these features.
10643            pkg.mOriginalPackages = null;
10644            pkg.mRealPackage = null;
10645            pkg.mAdoptPermissions = null;
10646        }
10647    }
10648
10649    /**
10650     * Asserts the parsed package is valid according to the given policy. If the
10651     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
10652     * <p>
10653     * Implementation detail: This method must NOT have any side effects. It would
10654     * ideally be static, but, it requires locks to read system state.
10655     *
10656     * @throws PackageManagerException If the package fails any of the validation checks
10657     */
10658    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
10659            throws PackageManagerException {
10660        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
10661            assertCodePolicy(pkg);
10662        }
10663
10664        if (pkg.applicationInfo.getCodePath() == null ||
10665                pkg.applicationInfo.getResourcePath() == null) {
10666            // Bail out. The resource and code paths haven't been set.
10667            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10668                    "Code and resource paths haven't been set correctly");
10669        }
10670
10671        // Make sure we're not adding any bogus keyset info
10672        KeySetManagerService ksms = mSettings.mKeySetManagerService;
10673        ksms.assertScannedPackageValid(pkg);
10674
10675        synchronized (mPackages) {
10676            // The special "android" package can only be defined once
10677            if (pkg.packageName.equals("android")) {
10678                if (mAndroidApplication != null) {
10679                    Slog.w(TAG, "*************************************************");
10680                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
10681                    Slog.w(TAG, " codePath=" + pkg.codePath);
10682                    Slog.w(TAG, "*************************************************");
10683                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10684                            "Core android package being redefined.  Skipping.");
10685                }
10686            }
10687
10688            // A package name must be unique; don't allow duplicates
10689            if (mPackages.containsKey(pkg.packageName)) {
10690                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10691                        "Application package " + pkg.packageName
10692                        + " already installed.  Skipping duplicate.");
10693            }
10694
10695            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10696                // Static libs have a synthetic package name containing the version
10697                // but we still want the base name to be unique.
10698                if (mPackages.containsKey(pkg.manifestPackageName)) {
10699                    throw new PackageManagerException(
10700                            "Duplicate static shared lib provider package");
10701                }
10702
10703                // Static shared libraries should have at least O target SDK
10704                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
10705                    throw new PackageManagerException(
10706                            "Packages declaring static-shared libs must target O SDK or higher");
10707                }
10708
10709                // Package declaring static a shared lib cannot be instant apps
10710                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10711                    throw new PackageManagerException(
10712                            "Packages declaring static-shared libs cannot be instant apps");
10713                }
10714
10715                // Package declaring static a shared lib cannot be renamed since the package
10716                // name is synthetic and apps can't code around package manager internals.
10717                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
10718                    throw new PackageManagerException(
10719                            "Packages declaring static-shared libs cannot be renamed");
10720                }
10721
10722                // Package declaring static a shared lib cannot declare child packages
10723                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
10724                    throw new PackageManagerException(
10725                            "Packages declaring static-shared libs cannot have child packages");
10726                }
10727
10728                // Package declaring static a shared lib cannot declare dynamic libs
10729                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
10730                    throw new PackageManagerException(
10731                            "Packages declaring static-shared libs cannot declare dynamic libs");
10732                }
10733
10734                // Package declaring static a shared lib cannot declare shared users
10735                if (pkg.mSharedUserId != null) {
10736                    throw new PackageManagerException(
10737                            "Packages declaring static-shared libs cannot declare shared users");
10738                }
10739
10740                // Static shared libs cannot declare activities
10741                if (!pkg.activities.isEmpty()) {
10742                    throw new PackageManagerException(
10743                            "Static shared libs cannot declare activities");
10744                }
10745
10746                // Static shared libs cannot declare services
10747                if (!pkg.services.isEmpty()) {
10748                    throw new PackageManagerException(
10749                            "Static shared libs cannot declare services");
10750                }
10751
10752                // Static shared libs cannot declare providers
10753                if (!pkg.providers.isEmpty()) {
10754                    throw new PackageManagerException(
10755                            "Static shared libs cannot declare content providers");
10756                }
10757
10758                // Static shared libs cannot declare receivers
10759                if (!pkg.receivers.isEmpty()) {
10760                    throw new PackageManagerException(
10761                            "Static shared libs cannot declare broadcast receivers");
10762                }
10763
10764                // Static shared libs cannot declare permission groups
10765                if (!pkg.permissionGroups.isEmpty()) {
10766                    throw new PackageManagerException(
10767                            "Static shared libs cannot declare permission groups");
10768                }
10769
10770                // Static shared libs cannot declare permissions
10771                if (!pkg.permissions.isEmpty()) {
10772                    throw new PackageManagerException(
10773                            "Static shared libs cannot declare permissions");
10774                }
10775
10776                // Static shared libs cannot declare protected broadcasts
10777                if (pkg.protectedBroadcasts != null) {
10778                    throw new PackageManagerException(
10779                            "Static shared libs cannot declare protected broadcasts");
10780                }
10781
10782                // Static shared libs cannot be overlay targets
10783                if (pkg.mOverlayTarget != null) {
10784                    throw new PackageManagerException(
10785                            "Static shared libs cannot be overlay targets");
10786                }
10787
10788                // The version codes must be ordered as lib versions
10789                int minVersionCode = Integer.MIN_VALUE;
10790                int maxVersionCode = Integer.MAX_VALUE;
10791
10792                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10793                        pkg.staticSharedLibName);
10794                if (versionedLib != null) {
10795                    final int versionCount = versionedLib.size();
10796                    for (int i = 0; i < versionCount; i++) {
10797                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
10798                        final int libVersionCode = libInfo.getDeclaringPackage()
10799                                .getVersionCode();
10800                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
10801                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
10802                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
10803                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
10804                        } else {
10805                            minVersionCode = maxVersionCode = libVersionCode;
10806                            break;
10807                        }
10808                    }
10809                }
10810                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
10811                    throw new PackageManagerException("Static shared"
10812                            + " lib version codes must be ordered as lib versions");
10813                }
10814            }
10815
10816            // Only privileged apps and updated privileged apps can add child packages.
10817            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
10818                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
10819                    throw new PackageManagerException("Only privileged apps can add child "
10820                            + "packages. Ignoring package " + pkg.packageName);
10821                }
10822                final int childCount = pkg.childPackages.size();
10823                for (int i = 0; i < childCount; i++) {
10824                    PackageParser.Package childPkg = pkg.childPackages.get(i);
10825                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
10826                            childPkg.packageName)) {
10827                        throw new PackageManagerException("Can't override child of "
10828                                + "another disabled app. Ignoring package " + pkg.packageName);
10829                    }
10830                }
10831            }
10832
10833            // If we're only installing presumed-existing packages, require that the
10834            // scanned APK is both already known and at the path previously established
10835            // for it.  Previously unknown packages we pick up normally, but if we have an
10836            // a priori expectation about this package's install presence, enforce it.
10837            // With a singular exception for new system packages. When an OTA contains
10838            // a new system package, we allow the codepath to change from a system location
10839            // to the user-installed location. If we don't allow this change, any newer,
10840            // user-installed version of the application will be ignored.
10841            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
10842                if (mExpectingBetter.containsKey(pkg.packageName)) {
10843                    logCriticalInfo(Log.WARN,
10844                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
10845                } else {
10846                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
10847                    if (known != null) {
10848                        if (DEBUG_PACKAGE_SCANNING) {
10849                            Log.d(TAG, "Examining " + pkg.codePath
10850                                    + " and requiring known paths " + known.codePathString
10851                                    + " & " + known.resourcePathString);
10852                        }
10853                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
10854                                || !pkg.applicationInfo.getResourcePath().equals(
10855                                        known.resourcePathString)) {
10856                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
10857                                    "Application package " + pkg.packageName
10858                                    + " found at " + pkg.applicationInfo.getCodePath()
10859                                    + " but expected at " + known.codePathString
10860                                    + "; ignoring.");
10861                        }
10862                    }
10863                }
10864            }
10865
10866            // Verify that this new package doesn't have any content providers
10867            // that conflict with existing packages.  Only do this if the
10868            // package isn't already installed, since we don't want to break
10869            // things that are installed.
10870            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
10871                final int N = pkg.providers.size();
10872                int i;
10873                for (i=0; i<N; i++) {
10874                    PackageParser.Provider p = pkg.providers.get(i);
10875                    if (p.info.authority != null) {
10876                        String names[] = p.info.authority.split(";");
10877                        for (int j = 0; j < names.length; j++) {
10878                            if (mProvidersByAuthority.containsKey(names[j])) {
10879                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10880                                final String otherPackageName =
10881                                        ((other != null && other.getComponentName() != null) ?
10882                                                other.getComponentName().getPackageName() : "?");
10883                                throw new PackageManagerException(
10884                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
10885                                        "Can't install because provider name " + names[j]
10886                                                + " (in package " + pkg.applicationInfo.packageName
10887                                                + ") is already used by " + otherPackageName);
10888                            }
10889                        }
10890                    }
10891                }
10892            }
10893        }
10894    }
10895
10896    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
10897            int type, String declaringPackageName, int declaringVersionCode) {
10898        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10899        if (versionedLib == null) {
10900            versionedLib = new SparseArray<>();
10901            mSharedLibraries.put(name, versionedLib);
10902            if (type == SharedLibraryInfo.TYPE_STATIC) {
10903                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
10904            }
10905        } else if (versionedLib.indexOfKey(version) >= 0) {
10906            return false;
10907        }
10908        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
10909                version, type, declaringPackageName, declaringVersionCode);
10910        versionedLib.put(version, libEntry);
10911        return true;
10912    }
10913
10914    private boolean removeSharedLibraryLPw(String name, int version) {
10915        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10916        if (versionedLib == null) {
10917            return false;
10918        }
10919        final int libIdx = versionedLib.indexOfKey(version);
10920        if (libIdx < 0) {
10921            return false;
10922        }
10923        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
10924        versionedLib.remove(version);
10925        if (versionedLib.size() <= 0) {
10926            mSharedLibraries.remove(name);
10927            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
10928                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
10929                        .getPackageName());
10930            }
10931        }
10932        return true;
10933    }
10934
10935    /**
10936     * Adds a scanned package to the system. When this method is finished, the package will
10937     * be available for query, resolution, etc...
10938     */
10939    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
10940            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
10941        final String pkgName = pkg.packageName;
10942        if (mCustomResolverComponentName != null &&
10943                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
10944            setUpCustomResolverActivity(pkg);
10945        }
10946
10947        if (pkg.packageName.equals("android")) {
10948            synchronized (mPackages) {
10949                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10950                    // Set up information for our fall-back user intent resolution activity.
10951                    mPlatformPackage = pkg;
10952                    pkg.mVersionCode = mSdkVersion;
10953                    mAndroidApplication = pkg.applicationInfo;
10954                    if (!mResolverReplaced) {
10955                        mResolveActivity.applicationInfo = mAndroidApplication;
10956                        mResolveActivity.name = ResolverActivity.class.getName();
10957                        mResolveActivity.packageName = mAndroidApplication.packageName;
10958                        mResolveActivity.processName = "system:ui";
10959                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10960                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
10961                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
10962                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
10963                        mResolveActivity.exported = true;
10964                        mResolveActivity.enabled = true;
10965                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
10966                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
10967                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
10968                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
10969                                | ActivityInfo.CONFIG_ORIENTATION
10970                                | ActivityInfo.CONFIG_KEYBOARD
10971                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
10972                        mResolveInfo.activityInfo = mResolveActivity;
10973                        mResolveInfo.priority = 0;
10974                        mResolveInfo.preferredOrder = 0;
10975                        mResolveInfo.match = 0;
10976                        mResolveComponentName = new ComponentName(
10977                                mAndroidApplication.packageName, mResolveActivity.name);
10978                    }
10979                }
10980            }
10981        }
10982
10983        ArrayList<PackageParser.Package> clientLibPkgs = null;
10984        // writer
10985        synchronized (mPackages) {
10986            boolean hasStaticSharedLibs = false;
10987
10988            // Any app can add new static shared libraries
10989            if (pkg.staticSharedLibName != null) {
10990                // Static shared libs don't allow renaming as they have synthetic package
10991                // names to allow install of multiple versions, so use name from manifest.
10992                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
10993                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
10994                        pkg.manifestPackageName, pkg.mVersionCode)) {
10995                    hasStaticSharedLibs = true;
10996                } else {
10997                    Slog.w(TAG, "Package " + pkg.packageName + " library "
10998                                + pkg.staticSharedLibName + " already exists; skipping");
10999                }
11000                // Static shared libs cannot be updated once installed since they
11001                // use synthetic package name which includes the version code, so
11002                // not need to update other packages's shared lib dependencies.
11003            }
11004
11005            if (!hasStaticSharedLibs
11006                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11007                // Only system apps can add new dynamic shared libraries.
11008                if (pkg.libraryNames != null) {
11009                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
11010                        String name = pkg.libraryNames.get(i);
11011                        boolean allowed = false;
11012                        if (pkg.isUpdatedSystemApp()) {
11013                            // New library entries can only be added through the
11014                            // system image.  This is important to get rid of a lot
11015                            // of nasty edge cases: for example if we allowed a non-
11016                            // system update of the app to add a library, then uninstalling
11017                            // the update would make the library go away, and assumptions
11018                            // we made such as through app install filtering would now
11019                            // have allowed apps on the device which aren't compatible
11020                            // with it.  Better to just have the restriction here, be
11021                            // conservative, and create many fewer cases that can negatively
11022                            // impact the user experience.
11023                            final PackageSetting sysPs = mSettings
11024                                    .getDisabledSystemPkgLPr(pkg.packageName);
11025                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
11026                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
11027                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
11028                                        allowed = true;
11029                                        break;
11030                                    }
11031                                }
11032                            }
11033                        } else {
11034                            allowed = true;
11035                        }
11036                        if (allowed) {
11037                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
11038                                    SharedLibraryInfo.VERSION_UNDEFINED,
11039                                    SharedLibraryInfo.TYPE_DYNAMIC,
11040                                    pkg.packageName, pkg.mVersionCode)) {
11041                                Slog.w(TAG, "Package " + pkg.packageName + " library "
11042                                        + name + " already exists; skipping");
11043                            }
11044                        } else {
11045                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
11046                                    + name + " that is not declared on system image; skipping");
11047                        }
11048                    }
11049
11050                    if ((scanFlags & SCAN_BOOTING) == 0) {
11051                        // If we are not booting, we need to update any applications
11052                        // that are clients of our shared library.  If we are booting,
11053                        // this will all be done once the scan is complete.
11054                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
11055                    }
11056                }
11057            }
11058        }
11059
11060        if ((scanFlags & SCAN_BOOTING) != 0) {
11061            // No apps can run during boot scan, so they don't need to be frozen
11062        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
11063            // Caller asked to not kill app, so it's probably not frozen
11064        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
11065            // Caller asked us to ignore frozen check for some reason; they
11066            // probably didn't know the package name
11067        } else {
11068            // We're doing major surgery on this package, so it better be frozen
11069            // right now to keep it from launching
11070            checkPackageFrozen(pkgName);
11071        }
11072
11073        // Also need to kill any apps that are dependent on the library.
11074        if (clientLibPkgs != null) {
11075            for (int i=0; i<clientLibPkgs.size(); i++) {
11076                PackageParser.Package clientPkg = clientLibPkgs.get(i);
11077                killApplication(clientPkg.applicationInfo.packageName,
11078                        clientPkg.applicationInfo.uid, "update lib");
11079            }
11080        }
11081
11082        // writer
11083        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
11084
11085        synchronized (mPackages) {
11086            // We don't expect installation to fail beyond this point
11087
11088            // Add the new setting to mSettings
11089            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
11090            // Add the new setting to mPackages
11091            mPackages.put(pkg.applicationInfo.packageName, pkg);
11092            // Make sure we don't accidentally delete its data.
11093            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
11094            while (iter.hasNext()) {
11095                PackageCleanItem item = iter.next();
11096                if (pkgName.equals(item.packageName)) {
11097                    iter.remove();
11098                }
11099            }
11100
11101            // Add the package's KeySets to the global KeySetManagerService
11102            KeySetManagerService ksms = mSettings.mKeySetManagerService;
11103            ksms.addScannedPackageLPw(pkg);
11104
11105            int N = pkg.providers.size();
11106            StringBuilder r = null;
11107            int i;
11108            for (i=0; i<N; i++) {
11109                PackageParser.Provider p = pkg.providers.get(i);
11110                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11111                        p.info.processName);
11112                mProviders.addProvider(p);
11113                p.syncable = p.info.isSyncable;
11114                if (p.info.authority != null) {
11115                    String names[] = p.info.authority.split(";");
11116                    p.info.authority = null;
11117                    for (int j = 0; j < names.length; j++) {
11118                        if (j == 1 && p.syncable) {
11119                            // We only want the first authority for a provider to possibly be
11120                            // syncable, so if we already added this provider using a different
11121                            // authority clear the syncable flag. We copy the provider before
11122                            // changing it because the mProviders object contains a reference
11123                            // to a provider that we don't want to change.
11124                            // Only do this for the second authority since the resulting provider
11125                            // object can be the same for all future authorities for this provider.
11126                            p = new PackageParser.Provider(p);
11127                            p.syncable = false;
11128                        }
11129                        if (!mProvidersByAuthority.containsKey(names[j])) {
11130                            mProvidersByAuthority.put(names[j], p);
11131                            if (p.info.authority == null) {
11132                                p.info.authority = names[j];
11133                            } else {
11134                                p.info.authority = p.info.authority + ";" + names[j];
11135                            }
11136                            if (DEBUG_PACKAGE_SCANNING) {
11137                                if (chatty)
11138                                    Log.d(TAG, "Registered content provider: " + names[j]
11139                                            + ", className = " + p.info.name + ", isSyncable = "
11140                                            + p.info.isSyncable);
11141                            }
11142                        } else {
11143                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11144                            Slog.w(TAG, "Skipping provider name " + names[j] +
11145                                    " (in package " + pkg.applicationInfo.packageName +
11146                                    "): name already used by "
11147                                    + ((other != null && other.getComponentName() != null)
11148                                            ? other.getComponentName().getPackageName() : "?"));
11149                        }
11150                    }
11151                }
11152                if (chatty) {
11153                    if (r == null) {
11154                        r = new StringBuilder(256);
11155                    } else {
11156                        r.append(' ');
11157                    }
11158                    r.append(p.info.name);
11159                }
11160            }
11161            if (r != null) {
11162                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
11163            }
11164
11165            N = pkg.services.size();
11166            r = null;
11167            for (i=0; i<N; i++) {
11168                PackageParser.Service s = pkg.services.get(i);
11169                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11170                        s.info.processName);
11171                mServices.addService(s);
11172                if (chatty) {
11173                    if (r == null) {
11174                        r = new StringBuilder(256);
11175                    } else {
11176                        r.append(' ');
11177                    }
11178                    r.append(s.info.name);
11179                }
11180            }
11181            if (r != null) {
11182                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
11183            }
11184
11185            N = pkg.receivers.size();
11186            r = null;
11187            for (i=0; i<N; i++) {
11188                PackageParser.Activity a = pkg.receivers.get(i);
11189                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11190                        a.info.processName);
11191                mReceivers.addActivity(a, "receiver");
11192                if (chatty) {
11193                    if (r == null) {
11194                        r = new StringBuilder(256);
11195                    } else {
11196                        r.append(' ');
11197                    }
11198                    r.append(a.info.name);
11199                }
11200            }
11201            if (r != null) {
11202                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11203            }
11204
11205            N = pkg.activities.size();
11206            r = null;
11207            for (i=0; i<N; i++) {
11208                PackageParser.Activity a = pkg.activities.get(i);
11209                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11210                        a.info.processName);
11211                mActivities.addActivity(a, "activity");
11212                if (chatty) {
11213                    if (r == null) {
11214                        r = new StringBuilder(256);
11215                    } else {
11216                        r.append(' ');
11217                    }
11218                    r.append(a.info.name);
11219                }
11220            }
11221            if (r != null) {
11222                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11223            }
11224
11225            N = pkg.permissionGroups.size();
11226            r = null;
11227            for (i=0; i<N; i++) {
11228                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
11229                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
11230                final String curPackageName = cur == null ? null : cur.info.packageName;
11231                // Dont allow ephemeral apps to define new permission groups.
11232                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11233                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11234                            + pg.info.packageName
11235                            + " ignored: instant apps cannot define new permission groups.");
11236                    continue;
11237                }
11238                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
11239                if (cur == null || isPackageUpdate) {
11240                    mPermissionGroups.put(pg.info.name, pg);
11241                    if (chatty) {
11242                        if (r == null) {
11243                            r = new StringBuilder(256);
11244                        } else {
11245                            r.append(' ');
11246                        }
11247                        if (isPackageUpdate) {
11248                            r.append("UPD:");
11249                        }
11250                        r.append(pg.info.name);
11251                    }
11252                } else {
11253                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11254                            + pg.info.packageName + " ignored: original from "
11255                            + cur.info.packageName);
11256                    if (chatty) {
11257                        if (r == null) {
11258                            r = new StringBuilder(256);
11259                        } else {
11260                            r.append(' ');
11261                        }
11262                        r.append("DUP:");
11263                        r.append(pg.info.name);
11264                    }
11265                }
11266            }
11267            if (r != null) {
11268                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
11269            }
11270
11271            N = pkg.permissions.size();
11272            r = null;
11273            for (i=0; i<N; i++) {
11274                PackageParser.Permission p = pkg.permissions.get(i);
11275
11276                // Dont allow ephemeral apps to define new permissions.
11277                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11278                    Slog.w(TAG, "Permission " + p.info.name + " from package "
11279                            + p.info.packageName
11280                            + " ignored: instant apps cannot define new permissions.");
11281                    continue;
11282                }
11283
11284                // Assume by default that we did not install this permission into the system.
11285                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
11286
11287                // Now that permission groups have a special meaning, we ignore permission
11288                // groups for legacy apps to prevent unexpected behavior. In particular,
11289                // permissions for one app being granted to someone just because they happen
11290                // to be in a group defined by another app (before this had no implications).
11291                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
11292                    p.group = mPermissionGroups.get(p.info.group);
11293                    // Warn for a permission in an unknown group.
11294                    if (DEBUG_PERMISSIONS && p.info.group != null && p.group == null) {
11295                        Slog.i(TAG, "Permission " + p.info.name + " from package "
11296                                + p.info.packageName + " in an unknown group " + p.info.group);
11297                    }
11298                }
11299
11300                ArrayMap<String, BasePermission> permissionMap =
11301                        p.tree ? mSettings.mPermissionTrees
11302                                : mSettings.mPermissions;
11303                BasePermission bp = permissionMap.get(p.info.name);
11304
11305                // Allow system apps to redefine non-system permissions
11306                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
11307                    final boolean currentOwnerIsSystem = (bp.perm != null
11308                            && isSystemApp(bp.perm.owner));
11309                    if (isSystemApp(p.owner)) {
11310                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
11311                            // It's a built-in permission and no owner, take ownership now
11312                            bp.packageSetting = pkgSetting;
11313                            bp.perm = p;
11314                            bp.uid = pkg.applicationInfo.uid;
11315                            bp.sourcePackage = p.info.packageName;
11316                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11317                        } else if (!currentOwnerIsSystem) {
11318                            String msg = "New decl " + p.owner + " of permission  "
11319                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
11320                            reportSettingsProblem(Log.WARN, msg);
11321                            bp = null;
11322                        }
11323                    }
11324                }
11325
11326                if (bp == null) {
11327                    bp = new BasePermission(p.info.name, p.info.packageName,
11328                            BasePermission.TYPE_NORMAL);
11329                    permissionMap.put(p.info.name, bp);
11330                }
11331
11332                if (bp.perm == null) {
11333                    if (bp.sourcePackage == null
11334                            || bp.sourcePackage.equals(p.info.packageName)) {
11335                        BasePermission tree = findPermissionTreeLP(p.info.name);
11336                        if (tree == null
11337                                || tree.sourcePackage.equals(p.info.packageName)) {
11338                            bp.packageSetting = pkgSetting;
11339                            bp.perm = p;
11340                            bp.uid = pkg.applicationInfo.uid;
11341                            bp.sourcePackage = p.info.packageName;
11342                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11343                            if (chatty) {
11344                                if (r == null) {
11345                                    r = new StringBuilder(256);
11346                                } else {
11347                                    r.append(' ');
11348                                }
11349                                r.append(p.info.name);
11350                            }
11351                        } else {
11352                            Slog.w(TAG, "Permission " + p.info.name + " from package "
11353                                    + p.info.packageName + " ignored: base tree "
11354                                    + tree.name + " is from package "
11355                                    + tree.sourcePackage);
11356                        }
11357                    } else {
11358                        Slog.w(TAG, "Permission " + p.info.name + " from package "
11359                                + p.info.packageName + " ignored: original from "
11360                                + bp.sourcePackage);
11361                    }
11362                } else if (chatty) {
11363                    if (r == null) {
11364                        r = new StringBuilder(256);
11365                    } else {
11366                        r.append(' ');
11367                    }
11368                    r.append("DUP:");
11369                    r.append(p.info.name);
11370                }
11371                if (bp.perm == p) {
11372                    bp.protectionLevel = p.info.protectionLevel;
11373                }
11374            }
11375
11376            if (r != null) {
11377                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
11378            }
11379
11380            N = pkg.instrumentation.size();
11381            r = null;
11382            for (i=0; i<N; i++) {
11383                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11384                a.info.packageName = pkg.applicationInfo.packageName;
11385                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11386                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11387                a.info.splitNames = pkg.splitNames;
11388                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11389                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11390                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11391                a.info.dataDir = pkg.applicationInfo.dataDir;
11392                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11393                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11394                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11395                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11396                mInstrumentation.put(a.getComponentName(), a);
11397                if (chatty) {
11398                    if (r == null) {
11399                        r = new StringBuilder(256);
11400                    } else {
11401                        r.append(' ');
11402                    }
11403                    r.append(a.info.name);
11404                }
11405            }
11406            if (r != null) {
11407                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
11408            }
11409
11410            if (pkg.protectedBroadcasts != null) {
11411                N = pkg.protectedBroadcasts.size();
11412                for (i=0; i<N; i++) {
11413                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11414                }
11415            }
11416        }
11417
11418        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11419    }
11420
11421    /**
11422     * Derive the ABI of a non-system package located at {@code scanFile}. This information
11423     * is derived purely on the basis of the contents of {@code scanFile} and
11424     * {@code cpuAbiOverride}.
11425     *
11426     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
11427     */
11428    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
11429                                 String cpuAbiOverride, boolean extractLibs,
11430                                 File appLib32InstallDir)
11431            throws PackageManagerException {
11432        // Give ourselves some initial paths; we'll come back for another
11433        // pass once we've determined ABI below.
11434        setNativeLibraryPaths(pkg, appLib32InstallDir);
11435
11436        // We would never need to extract libs for forward-locked and external packages,
11437        // since the container service will do it for us. We shouldn't attempt to
11438        // extract libs from system app when it was not updated.
11439        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
11440                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
11441            extractLibs = false;
11442        }
11443
11444        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
11445        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
11446
11447        NativeLibraryHelper.Handle handle = null;
11448        try {
11449            handle = NativeLibraryHelper.Handle.create(pkg);
11450            // TODO(multiArch): This can be null for apps that didn't go through the
11451            // usual installation process. We can calculate it again, like we
11452            // do during install time.
11453            //
11454            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
11455            // unnecessary.
11456            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
11457
11458            // Null out the abis so that they can be recalculated.
11459            pkg.applicationInfo.primaryCpuAbi = null;
11460            pkg.applicationInfo.secondaryCpuAbi = null;
11461            if (isMultiArch(pkg.applicationInfo)) {
11462                // Warn if we've set an abiOverride for multi-lib packages..
11463                // By definition, we need to copy both 32 and 64 bit libraries for
11464                // such packages.
11465                if (pkg.cpuAbiOverride != null
11466                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
11467                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
11468                }
11469
11470                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
11471                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
11472                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
11473                    if (extractLibs) {
11474                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11475                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11476                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
11477                                useIsaSpecificSubdirs);
11478                    } else {
11479                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11480                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
11481                    }
11482                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11483                }
11484
11485                // Shared library native code should be in the APK zip aligned
11486                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
11487                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11488                            "Shared library native lib extraction not supported");
11489                }
11490
11491                maybeThrowExceptionForMultiArchCopy(
11492                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
11493
11494                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
11495                    if (extractLibs) {
11496                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11497                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11498                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
11499                                useIsaSpecificSubdirs);
11500                    } else {
11501                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11502                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
11503                    }
11504                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11505                }
11506
11507                maybeThrowExceptionForMultiArchCopy(
11508                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
11509
11510                if (abi64 >= 0) {
11511                    // Shared library native libs should be in the APK zip aligned
11512                    if (extractLibs && pkg.isLibrary()) {
11513                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11514                                "Shared library native lib extraction not supported");
11515                    }
11516                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
11517                }
11518
11519                if (abi32 >= 0) {
11520                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
11521                    if (abi64 >= 0) {
11522                        if (pkg.use32bitAbi) {
11523                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11524                            pkg.applicationInfo.primaryCpuAbi = abi;
11525                        } else {
11526                            pkg.applicationInfo.secondaryCpuAbi = abi;
11527                        }
11528                    } else {
11529                        pkg.applicationInfo.primaryCpuAbi = abi;
11530                    }
11531                }
11532            } else {
11533                String[] abiList = (cpuAbiOverride != null) ?
11534                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
11535
11536                // Enable gross and lame hacks for apps that are built with old
11537                // SDK tools. We must scan their APKs for renderscript bitcode and
11538                // not launch them if it's present. Don't bother checking on devices
11539                // that don't have 64 bit support.
11540                boolean needsRenderScriptOverride = false;
11541                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
11542                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
11543                    abiList = Build.SUPPORTED_32_BIT_ABIS;
11544                    needsRenderScriptOverride = true;
11545                }
11546
11547                final int copyRet;
11548                if (extractLibs) {
11549                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11550                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11551                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
11552                } else {
11553                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11554                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
11555                }
11556                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11557
11558                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
11559                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11560                            "Error unpackaging native libs for app, errorCode=" + copyRet);
11561                }
11562
11563                if (copyRet >= 0) {
11564                    // Shared libraries that have native libs must be multi-architecture
11565                    if (pkg.isLibrary()) {
11566                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11567                                "Shared library with native libs must be multiarch");
11568                    }
11569                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
11570                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
11571                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
11572                } else if (needsRenderScriptOverride) {
11573                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
11574                }
11575            }
11576        } catch (IOException ioe) {
11577            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
11578        } finally {
11579            IoUtils.closeQuietly(handle);
11580        }
11581
11582        // Now that we've calculated the ABIs and determined if it's an internal app,
11583        // we will go ahead and populate the nativeLibraryPath.
11584        setNativeLibraryPaths(pkg, appLib32InstallDir);
11585    }
11586
11587    /**
11588     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
11589     * i.e, so that all packages can be run inside a single process if required.
11590     *
11591     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
11592     * this function will either try and make the ABI for all packages in {@code packagesForUser}
11593     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
11594     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
11595     * updating a package that belongs to a shared user.
11596     *
11597     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
11598     * adds unnecessary complexity.
11599     */
11600    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
11601            PackageParser.Package scannedPackage) {
11602        String requiredInstructionSet = null;
11603        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
11604            requiredInstructionSet = VMRuntime.getInstructionSet(
11605                     scannedPackage.applicationInfo.primaryCpuAbi);
11606        }
11607
11608        PackageSetting requirer = null;
11609        for (PackageSetting ps : packagesForUser) {
11610            // If packagesForUser contains scannedPackage, we skip it. This will happen
11611            // when scannedPackage is an update of an existing package. Without this check,
11612            // we will never be able to change the ABI of any package belonging to a shared
11613            // user, even if it's compatible with other packages.
11614            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11615                if (ps.primaryCpuAbiString == null) {
11616                    continue;
11617                }
11618
11619                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
11620                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
11621                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
11622                    // this but there's not much we can do.
11623                    String errorMessage = "Instruction set mismatch, "
11624                            + ((requirer == null) ? "[caller]" : requirer)
11625                            + " requires " + requiredInstructionSet + " whereas " + ps
11626                            + " requires " + instructionSet;
11627                    Slog.w(TAG, errorMessage);
11628                }
11629
11630                if (requiredInstructionSet == null) {
11631                    requiredInstructionSet = instructionSet;
11632                    requirer = ps;
11633                }
11634            }
11635        }
11636
11637        if (requiredInstructionSet != null) {
11638            String adjustedAbi;
11639            if (requirer != null) {
11640                // requirer != null implies that either scannedPackage was null or that scannedPackage
11641                // did not require an ABI, in which case we have to adjust scannedPackage to match
11642                // the ABI of the set (which is the same as requirer's ABI)
11643                adjustedAbi = requirer.primaryCpuAbiString;
11644                if (scannedPackage != null) {
11645                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
11646                }
11647            } else {
11648                // requirer == null implies that we're updating all ABIs in the set to
11649                // match scannedPackage.
11650                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
11651            }
11652
11653            for (PackageSetting ps : packagesForUser) {
11654                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11655                    if (ps.primaryCpuAbiString != null) {
11656                        continue;
11657                    }
11658
11659                    ps.primaryCpuAbiString = adjustedAbi;
11660                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
11661                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
11662                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
11663                        if (DEBUG_ABI_SELECTION) {
11664                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
11665                                    + " (requirer="
11666                                    + (requirer != null ? requirer.pkg : "null")
11667                                    + ", scannedPackage="
11668                                    + (scannedPackage != null ? scannedPackage : "null")
11669                                    + ")");
11670                        }
11671                        try {
11672                            mInstaller.rmdex(ps.codePathString,
11673                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
11674                        } catch (InstallerException ignored) {
11675                        }
11676                    }
11677                }
11678            }
11679        }
11680    }
11681
11682    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
11683        synchronized (mPackages) {
11684            mResolverReplaced = true;
11685            // Set up information for custom user intent resolution activity.
11686            mResolveActivity.applicationInfo = pkg.applicationInfo;
11687            mResolveActivity.name = mCustomResolverComponentName.getClassName();
11688            mResolveActivity.packageName = pkg.applicationInfo.packageName;
11689            mResolveActivity.processName = pkg.applicationInfo.packageName;
11690            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11691            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
11692                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11693            mResolveActivity.theme = 0;
11694            mResolveActivity.exported = true;
11695            mResolveActivity.enabled = true;
11696            mResolveInfo.activityInfo = mResolveActivity;
11697            mResolveInfo.priority = 0;
11698            mResolveInfo.preferredOrder = 0;
11699            mResolveInfo.match = 0;
11700            mResolveComponentName = mCustomResolverComponentName;
11701            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
11702                    mResolveComponentName);
11703        }
11704    }
11705
11706    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
11707        if (installerActivity == null) {
11708            if (DEBUG_EPHEMERAL) {
11709                Slog.d(TAG, "Clear ephemeral installer activity");
11710            }
11711            mInstantAppInstallerActivity = null;
11712            return;
11713        }
11714
11715        if (DEBUG_EPHEMERAL) {
11716            Slog.d(TAG, "Set ephemeral installer activity: "
11717                    + installerActivity.getComponentName());
11718        }
11719        // Set up information for ephemeral installer activity
11720        mInstantAppInstallerActivity = installerActivity;
11721        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
11722                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11723        mInstantAppInstallerActivity.exported = true;
11724        mInstantAppInstallerActivity.enabled = true;
11725        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
11726        mInstantAppInstallerInfo.priority = 0;
11727        mInstantAppInstallerInfo.preferredOrder = 1;
11728        mInstantAppInstallerInfo.isDefault = true;
11729        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
11730                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
11731    }
11732
11733    private static String calculateBundledApkRoot(final String codePathString) {
11734        final File codePath = new File(codePathString);
11735        final File codeRoot;
11736        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
11737            codeRoot = Environment.getRootDirectory();
11738        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
11739            codeRoot = Environment.getOemDirectory();
11740        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
11741            codeRoot = Environment.getVendorDirectory();
11742        } else {
11743            // Unrecognized code path; take its top real segment as the apk root:
11744            // e.g. /something/app/blah.apk => /something
11745            try {
11746                File f = codePath.getCanonicalFile();
11747                File parent = f.getParentFile();    // non-null because codePath is a file
11748                File tmp;
11749                while ((tmp = parent.getParentFile()) != null) {
11750                    f = parent;
11751                    parent = tmp;
11752                }
11753                codeRoot = f;
11754                Slog.w(TAG, "Unrecognized code path "
11755                        + codePath + " - using " + codeRoot);
11756            } catch (IOException e) {
11757                // Can't canonicalize the code path -- shenanigans?
11758                Slog.w(TAG, "Can't canonicalize code path " + codePath);
11759                return Environment.getRootDirectory().getPath();
11760            }
11761        }
11762        return codeRoot.getPath();
11763    }
11764
11765    /**
11766     * Derive and set the location of native libraries for the given package,
11767     * which varies depending on where and how the package was installed.
11768     */
11769    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
11770        final ApplicationInfo info = pkg.applicationInfo;
11771        final String codePath = pkg.codePath;
11772        final File codeFile = new File(codePath);
11773        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
11774        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
11775
11776        info.nativeLibraryRootDir = null;
11777        info.nativeLibraryRootRequiresIsa = false;
11778        info.nativeLibraryDir = null;
11779        info.secondaryNativeLibraryDir = null;
11780
11781        if (isApkFile(codeFile)) {
11782            // Monolithic install
11783            if (bundledApp) {
11784                // If "/system/lib64/apkname" exists, assume that is the per-package
11785                // native library directory to use; otherwise use "/system/lib/apkname".
11786                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
11787                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
11788                        getPrimaryInstructionSet(info));
11789
11790                // This is a bundled system app so choose the path based on the ABI.
11791                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
11792                // is just the default path.
11793                final String apkName = deriveCodePathName(codePath);
11794                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
11795                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
11796                        apkName).getAbsolutePath();
11797
11798                if (info.secondaryCpuAbi != null) {
11799                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
11800                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
11801                            secondaryLibDir, apkName).getAbsolutePath();
11802                }
11803            } else if (asecApp) {
11804                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
11805                        .getAbsolutePath();
11806            } else {
11807                final String apkName = deriveCodePathName(codePath);
11808                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
11809                        .getAbsolutePath();
11810            }
11811
11812            info.nativeLibraryRootRequiresIsa = false;
11813            info.nativeLibraryDir = info.nativeLibraryRootDir;
11814        } else {
11815            // Cluster install
11816            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
11817            info.nativeLibraryRootRequiresIsa = true;
11818
11819            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
11820                    getPrimaryInstructionSet(info)).getAbsolutePath();
11821
11822            if (info.secondaryCpuAbi != null) {
11823                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
11824                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
11825            }
11826        }
11827    }
11828
11829    /**
11830     * Calculate the abis and roots for a bundled app. These can uniquely
11831     * be determined from the contents of the system partition, i.e whether
11832     * it contains 64 or 32 bit shared libraries etc. We do not validate any
11833     * of this information, and instead assume that the system was built
11834     * sensibly.
11835     */
11836    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
11837                                           PackageSetting pkgSetting) {
11838        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
11839
11840        // If "/system/lib64/apkname" exists, assume that is the per-package
11841        // native library directory to use; otherwise use "/system/lib/apkname".
11842        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
11843        setBundledAppAbi(pkg, apkRoot, apkName);
11844        // pkgSetting might be null during rescan following uninstall of updates
11845        // to a bundled app, so accommodate that possibility.  The settings in
11846        // that case will be established later from the parsed package.
11847        //
11848        // If the settings aren't null, sync them up with what we've just derived.
11849        // note that apkRoot isn't stored in the package settings.
11850        if (pkgSetting != null) {
11851            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11852            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11853        }
11854    }
11855
11856    /**
11857     * Deduces the ABI of a bundled app and sets the relevant fields on the
11858     * parsed pkg object.
11859     *
11860     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
11861     *        under which system libraries are installed.
11862     * @param apkName the name of the installed package.
11863     */
11864    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
11865        final File codeFile = new File(pkg.codePath);
11866
11867        final boolean has64BitLibs;
11868        final boolean has32BitLibs;
11869        if (isApkFile(codeFile)) {
11870            // Monolithic install
11871            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
11872            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
11873        } else {
11874            // Cluster install
11875            final File rootDir = new File(codeFile, LIB_DIR_NAME);
11876            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
11877                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
11878                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
11879                has64BitLibs = (new File(rootDir, isa)).exists();
11880            } else {
11881                has64BitLibs = false;
11882            }
11883            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
11884                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
11885                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
11886                has32BitLibs = (new File(rootDir, isa)).exists();
11887            } else {
11888                has32BitLibs = false;
11889            }
11890        }
11891
11892        if (has64BitLibs && !has32BitLibs) {
11893            // The package has 64 bit libs, but not 32 bit libs. Its primary
11894            // ABI should be 64 bit. We can safely assume here that the bundled
11895            // native libraries correspond to the most preferred ABI in the list.
11896
11897            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11898            pkg.applicationInfo.secondaryCpuAbi = null;
11899        } else if (has32BitLibs && !has64BitLibs) {
11900            // The package has 32 bit libs but not 64 bit libs. Its primary
11901            // ABI should be 32 bit.
11902
11903            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11904            pkg.applicationInfo.secondaryCpuAbi = null;
11905        } else if (has32BitLibs && has64BitLibs) {
11906            // The application has both 64 and 32 bit bundled libraries. We check
11907            // here that the app declares multiArch support, and warn if it doesn't.
11908            //
11909            // We will be lenient here and record both ABIs. The primary will be the
11910            // ABI that's higher on the list, i.e, a device that's configured to prefer
11911            // 64 bit apps will see a 64 bit primary ABI,
11912
11913            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
11914                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
11915            }
11916
11917            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
11918                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11919                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11920            } else {
11921                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11922                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11923            }
11924        } else {
11925            pkg.applicationInfo.primaryCpuAbi = null;
11926            pkg.applicationInfo.secondaryCpuAbi = null;
11927        }
11928    }
11929
11930    private void killApplication(String pkgName, int appId, String reason) {
11931        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
11932    }
11933
11934    private void killApplication(String pkgName, int appId, int userId, String reason) {
11935        // Request the ActivityManager to kill the process(only for existing packages)
11936        // so that we do not end up in a confused state while the user is still using the older
11937        // version of the application while the new one gets installed.
11938        final long token = Binder.clearCallingIdentity();
11939        try {
11940            IActivityManager am = ActivityManager.getService();
11941            if (am != null) {
11942                try {
11943                    am.killApplication(pkgName, appId, userId, reason);
11944                } catch (RemoteException e) {
11945                }
11946            }
11947        } finally {
11948            Binder.restoreCallingIdentity(token);
11949        }
11950    }
11951
11952    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
11953        // Remove the parent package setting
11954        PackageSetting ps = (PackageSetting) pkg.mExtras;
11955        if (ps != null) {
11956            removePackageLI(ps, chatty);
11957        }
11958        // Remove the child package setting
11959        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11960        for (int i = 0; i < childCount; i++) {
11961            PackageParser.Package childPkg = pkg.childPackages.get(i);
11962            ps = (PackageSetting) childPkg.mExtras;
11963            if (ps != null) {
11964                removePackageLI(ps, chatty);
11965            }
11966        }
11967    }
11968
11969    void removePackageLI(PackageSetting ps, boolean chatty) {
11970        if (DEBUG_INSTALL) {
11971            if (chatty)
11972                Log.d(TAG, "Removing package " + ps.name);
11973        }
11974
11975        // writer
11976        synchronized (mPackages) {
11977            mPackages.remove(ps.name);
11978            final PackageParser.Package pkg = ps.pkg;
11979            if (pkg != null) {
11980                cleanPackageDataStructuresLILPw(pkg, chatty);
11981            }
11982        }
11983    }
11984
11985    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
11986        if (DEBUG_INSTALL) {
11987            if (chatty)
11988                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
11989        }
11990
11991        // writer
11992        synchronized (mPackages) {
11993            // Remove the parent package
11994            mPackages.remove(pkg.applicationInfo.packageName);
11995            cleanPackageDataStructuresLILPw(pkg, chatty);
11996
11997            // Remove the child packages
11998            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11999            for (int i = 0; i < childCount; i++) {
12000                PackageParser.Package childPkg = pkg.childPackages.get(i);
12001                mPackages.remove(childPkg.applicationInfo.packageName);
12002                cleanPackageDataStructuresLILPw(childPkg, chatty);
12003            }
12004        }
12005    }
12006
12007    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
12008        int N = pkg.providers.size();
12009        StringBuilder r = null;
12010        int i;
12011        for (i=0; i<N; i++) {
12012            PackageParser.Provider p = pkg.providers.get(i);
12013            mProviders.removeProvider(p);
12014            if (p.info.authority == null) {
12015
12016                /* There was another ContentProvider with this authority when
12017                 * this app was installed so this authority is null,
12018                 * Ignore it as we don't have to unregister the provider.
12019                 */
12020                continue;
12021            }
12022            String names[] = p.info.authority.split(";");
12023            for (int j = 0; j < names.length; j++) {
12024                if (mProvidersByAuthority.get(names[j]) == p) {
12025                    mProvidersByAuthority.remove(names[j]);
12026                    if (DEBUG_REMOVE) {
12027                        if (chatty)
12028                            Log.d(TAG, "Unregistered content provider: " + names[j]
12029                                    + ", className = " + p.info.name + ", isSyncable = "
12030                                    + p.info.isSyncable);
12031                    }
12032                }
12033            }
12034            if (DEBUG_REMOVE && chatty) {
12035                if (r == null) {
12036                    r = new StringBuilder(256);
12037                } else {
12038                    r.append(' ');
12039                }
12040                r.append(p.info.name);
12041            }
12042        }
12043        if (r != null) {
12044            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
12045        }
12046
12047        N = pkg.services.size();
12048        r = null;
12049        for (i=0; i<N; i++) {
12050            PackageParser.Service s = pkg.services.get(i);
12051            mServices.removeService(s);
12052            if (chatty) {
12053                if (r == null) {
12054                    r = new StringBuilder(256);
12055                } else {
12056                    r.append(' ');
12057                }
12058                r.append(s.info.name);
12059            }
12060        }
12061        if (r != null) {
12062            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
12063        }
12064
12065        N = pkg.receivers.size();
12066        r = null;
12067        for (i=0; i<N; i++) {
12068            PackageParser.Activity a = pkg.receivers.get(i);
12069            mReceivers.removeActivity(a, "receiver");
12070            if (DEBUG_REMOVE && chatty) {
12071                if (r == null) {
12072                    r = new StringBuilder(256);
12073                } else {
12074                    r.append(' ');
12075                }
12076                r.append(a.info.name);
12077            }
12078        }
12079        if (r != null) {
12080            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
12081        }
12082
12083        N = pkg.activities.size();
12084        r = null;
12085        for (i=0; i<N; i++) {
12086            PackageParser.Activity a = pkg.activities.get(i);
12087            mActivities.removeActivity(a, "activity");
12088            if (DEBUG_REMOVE && chatty) {
12089                if (r == null) {
12090                    r = new StringBuilder(256);
12091                } else {
12092                    r.append(' ');
12093                }
12094                r.append(a.info.name);
12095            }
12096        }
12097        if (r != null) {
12098            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
12099        }
12100
12101        N = pkg.permissions.size();
12102        r = null;
12103        for (i=0; i<N; i++) {
12104            PackageParser.Permission p = pkg.permissions.get(i);
12105            BasePermission bp = mSettings.mPermissions.get(p.info.name);
12106            if (bp == null) {
12107                bp = mSettings.mPermissionTrees.get(p.info.name);
12108            }
12109            if (bp != null && bp.perm == p) {
12110                bp.perm = null;
12111                if (DEBUG_REMOVE && chatty) {
12112                    if (r == null) {
12113                        r = new StringBuilder(256);
12114                    } else {
12115                        r.append(' ');
12116                    }
12117                    r.append(p.info.name);
12118                }
12119            }
12120            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12121                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
12122                if (appOpPkgs != null) {
12123                    appOpPkgs.remove(pkg.packageName);
12124                }
12125            }
12126        }
12127        if (r != null) {
12128            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12129        }
12130
12131        N = pkg.requestedPermissions.size();
12132        r = null;
12133        for (i=0; i<N; i++) {
12134            String perm = pkg.requestedPermissions.get(i);
12135            BasePermission bp = mSettings.mPermissions.get(perm);
12136            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12137                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
12138                if (appOpPkgs != null) {
12139                    appOpPkgs.remove(pkg.packageName);
12140                    if (appOpPkgs.isEmpty()) {
12141                        mAppOpPermissionPackages.remove(perm);
12142                    }
12143                }
12144            }
12145        }
12146        if (r != null) {
12147            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12148        }
12149
12150        N = pkg.instrumentation.size();
12151        r = null;
12152        for (i=0; i<N; i++) {
12153            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
12154            mInstrumentation.remove(a.getComponentName());
12155            if (DEBUG_REMOVE && chatty) {
12156                if (r == null) {
12157                    r = new StringBuilder(256);
12158                } else {
12159                    r.append(' ');
12160                }
12161                r.append(a.info.name);
12162            }
12163        }
12164        if (r != null) {
12165            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
12166        }
12167
12168        r = null;
12169        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
12170            // Only system apps can hold shared libraries.
12171            if (pkg.libraryNames != null) {
12172                for (i = 0; i < pkg.libraryNames.size(); i++) {
12173                    String name = pkg.libraryNames.get(i);
12174                    if (removeSharedLibraryLPw(name, 0)) {
12175                        if (DEBUG_REMOVE && chatty) {
12176                            if (r == null) {
12177                                r = new StringBuilder(256);
12178                            } else {
12179                                r.append(' ');
12180                            }
12181                            r.append(name);
12182                        }
12183                    }
12184                }
12185            }
12186        }
12187
12188        r = null;
12189
12190        // Any package can hold static shared libraries.
12191        if (pkg.staticSharedLibName != null) {
12192            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
12193                if (DEBUG_REMOVE && chatty) {
12194                    if (r == null) {
12195                        r = new StringBuilder(256);
12196                    } else {
12197                        r.append(' ');
12198                    }
12199                    r.append(pkg.staticSharedLibName);
12200                }
12201            }
12202        }
12203
12204        if (r != null) {
12205            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
12206        }
12207    }
12208
12209    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
12210        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
12211            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
12212                return true;
12213            }
12214        }
12215        return false;
12216    }
12217
12218    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
12219    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
12220    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
12221
12222    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
12223        // Update the parent permissions
12224        updatePermissionsLPw(pkg.packageName, pkg, flags);
12225        // Update the child permissions
12226        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12227        for (int i = 0; i < childCount; i++) {
12228            PackageParser.Package childPkg = pkg.childPackages.get(i);
12229            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
12230        }
12231    }
12232
12233    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
12234            int flags) {
12235        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
12236        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
12237    }
12238
12239    private void updatePermissionsLPw(String changingPkg,
12240            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
12241        // Make sure there are no dangling permission trees.
12242        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
12243        while (it.hasNext()) {
12244            final BasePermission bp = it.next();
12245            if (bp.packageSetting == null) {
12246                // We may not yet have parsed the package, so just see if
12247                // we still know about its settings.
12248                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12249            }
12250            if (bp.packageSetting == null) {
12251                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
12252                        + " from package " + bp.sourcePackage);
12253                it.remove();
12254            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12255                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12256                    Slog.i(TAG, "Removing old permission tree: " + bp.name
12257                            + " from package " + bp.sourcePackage);
12258                    flags |= UPDATE_PERMISSIONS_ALL;
12259                    it.remove();
12260                }
12261            }
12262        }
12263
12264        // Make sure all dynamic permissions have been assigned to a package,
12265        // and make sure there are no dangling permissions.
12266        it = mSettings.mPermissions.values().iterator();
12267        while (it.hasNext()) {
12268            final BasePermission bp = it.next();
12269            if (bp.type == BasePermission.TYPE_DYNAMIC) {
12270                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
12271                        + bp.name + " pkg=" + bp.sourcePackage
12272                        + " info=" + bp.pendingInfo);
12273                if (bp.packageSetting == null && bp.pendingInfo != null) {
12274                    final BasePermission tree = findPermissionTreeLP(bp.name);
12275                    if (tree != null && tree.perm != null) {
12276                        bp.packageSetting = tree.packageSetting;
12277                        bp.perm = new PackageParser.Permission(tree.perm.owner,
12278                                new PermissionInfo(bp.pendingInfo));
12279                        bp.perm.info.packageName = tree.perm.info.packageName;
12280                        bp.perm.info.name = bp.name;
12281                        bp.uid = tree.uid;
12282                    }
12283                }
12284            }
12285            if (bp.packageSetting == null) {
12286                // We may not yet have parsed the package, so just see if
12287                // we still know about its settings.
12288                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12289            }
12290            if (bp.packageSetting == null) {
12291                Slog.w(TAG, "Removing dangling permission: " + bp.name
12292                        + " from package " + bp.sourcePackage);
12293                it.remove();
12294            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12295                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12296                    Slog.i(TAG, "Removing old permission: " + bp.name
12297                            + " from package " + bp.sourcePackage);
12298                    flags |= UPDATE_PERMISSIONS_ALL;
12299                    it.remove();
12300                }
12301            }
12302        }
12303
12304        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
12305        // Now update the permissions for all packages, in particular
12306        // replace the granted permissions of the system packages.
12307        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
12308            for (PackageParser.Package pkg : mPackages.values()) {
12309                if (pkg != pkgInfo) {
12310                    // Only replace for packages on requested volume
12311                    final String volumeUuid = getVolumeUuidForPackage(pkg);
12312                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
12313                            && Objects.equals(replaceVolumeUuid, volumeUuid);
12314                    grantPermissionsLPw(pkg, replace, changingPkg);
12315                }
12316            }
12317        }
12318
12319        if (pkgInfo != null) {
12320            // Only replace for packages on requested volume
12321            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
12322            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
12323                    && Objects.equals(replaceVolumeUuid, volumeUuid);
12324            grantPermissionsLPw(pkgInfo, replace, changingPkg);
12325        }
12326        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12327    }
12328
12329    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
12330            String packageOfInterest) {
12331        // IMPORTANT: There are two types of permissions: install and runtime.
12332        // Install time permissions are granted when the app is installed to
12333        // all device users and users added in the future. Runtime permissions
12334        // are granted at runtime explicitly to specific users. Normal and signature
12335        // protected permissions are install time permissions. Dangerous permissions
12336        // are install permissions if the app's target SDK is Lollipop MR1 or older,
12337        // otherwise they are runtime permissions. This function does not manage
12338        // runtime permissions except for the case an app targeting Lollipop MR1
12339        // being upgraded to target a newer SDK, in which case dangerous permissions
12340        // are transformed from install time to runtime ones.
12341
12342        final PackageSetting ps = (PackageSetting) pkg.mExtras;
12343        if (ps == null) {
12344            return;
12345        }
12346
12347        PermissionsState permissionsState = ps.getPermissionsState();
12348        PermissionsState origPermissions = permissionsState;
12349
12350        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
12351
12352        boolean runtimePermissionsRevoked = false;
12353        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
12354
12355        boolean changedInstallPermission = false;
12356
12357        if (replace) {
12358            ps.installPermissionsFixed = false;
12359            if (!ps.isSharedUser()) {
12360                origPermissions = new PermissionsState(permissionsState);
12361                permissionsState.reset();
12362            } else {
12363                // We need to know only about runtime permission changes since the
12364                // calling code always writes the install permissions state but
12365                // the runtime ones are written only if changed. The only cases of
12366                // changed runtime permissions here are promotion of an install to
12367                // runtime and revocation of a runtime from a shared user.
12368                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
12369                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
12370                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
12371                    runtimePermissionsRevoked = true;
12372                }
12373            }
12374        }
12375
12376        permissionsState.setGlobalGids(mGlobalGids);
12377
12378        final int N = pkg.requestedPermissions.size();
12379        for (int i=0; i<N; i++) {
12380            final String name = pkg.requestedPermissions.get(i);
12381            final BasePermission bp = mSettings.mPermissions.get(name);
12382            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
12383                    >= Build.VERSION_CODES.M;
12384
12385            if (DEBUG_INSTALL) {
12386                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
12387            }
12388
12389            if (bp == null || bp.packageSetting == null) {
12390                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
12391                    if (DEBUG_PERMISSIONS) {
12392                        Slog.i(TAG, "Unknown permission " + name
12393                                + " in package " + pkg.packageName);
12394                    }
12395                }
12396                continue;
12397            }
12398
12399
12400            // Limit ephemeral apps to ephemeral allowed permissions.
12401            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
12402                if (DEBUG_PERMISSIONS) {
12403                    Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
12404                            + pkg.packageName);
12405                }
12406                continue;
12407            }
12408
12409            if (bp.isRuntimeOnly() && !appSupportsRuntimePermissions) {
12410                if (DEBUG_PERMISSIONS) {
12411                    Log.i(TAG, "Denying runtime-only permission " + bp.name + " for package "
12412                            + pkg.packageName);
12413                }
12414                continue;
12415            }
12416
12417            final String perm = bp.name;
12418            boolean allowedSig = false;
12419            int grant = GRANT_DENIED;
12420
12421            // Keep track of app op permissions.
12422            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12423                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
12424                if (pkgs == null) {
12425                    pkgs = new ArraySet<>();
12426                    mAppOpPermissionPackages.put(bp.name, pkgs);
12427                }
12428                pkgs.add(pkg.packageName);
12429            }
12430
12431            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
12432            switch (level) {
12433                case PermissionInfo.PROTECTION_NORMAL: {
12434                    // For all apps normal permissions are install time ones.
12435                    grant = GRANT_INSTALL;
12436                } break;
12437
12438                case PermissionInfo.PROTECTION_DANGEROUS: {
12439                    // If a permission review is required for legacy apps we represent
12440                    // their permissions as always granted runtime ones since we need
12441                    // to keep the review required permission flag per user while an
12442                    // install permission's state is shared across all users.
12443                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
12444                        // For legacy apps dangerous permissions are install time ones.
12445                        grant = GRANT_INSTALL;
12446                    } else if (origPermissions.hasInstallPermission(bp.name)) {
12447                        // For legacy apps that became modern, install becomes runtime.
12448                        grant = GRANT_UPGRADE;
12449                    } else if (mPromoteSystemApps
12450                            && isSystemApp(ps)
12451                            && mExistingSystemPackages.contains(ps.name)) {
12452                        // For legacy system apps, install becomes runtime.
12453                        // We cannot check hasInstallPermission() for system apps since those
12454                        // permissions were granted implicitly and not persisted pre-M.
12455                        grant = GRANT_UPGRADE;
12456                    } else {
12457                        // For modern apps keep runtime permissions unchanged.
12458                        grant = GRANT_RUNTIME;
12459                    }
12460                } break;
12461
12462                case PermissionInfo.PROTECTION_SIGNATURE: {
12463                    // For all apps signature permissions are install time ones.
12464                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
12465                    if (allowedSig) {
12466                        grant = GRANT_INSTALL;
12467                    }
12468                } break;
12469            }
12470
12471            if (DEBUG_PERMISSIONS) {
12472                Slog.i(TAG, "Granting permission " + perm + " to package " + pkg.packageName);
12473            }
12474
12475            if (grant != GRANT_DENIED) {
12476                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
12477                    // If this is an existing, non-system package, then
12478                    // we can't add any new permissions to it.
12479                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
12480                        // Except...  if this is a permission that was added
12481                        // to the platform (note: need to only do this when
12482                        // updating the platform).
12483                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
12484                            grant = GRANT_DENIED;
12485                        }
12486                    }
12487                }
12488
12489                switch (grant) {
12490                    case GRANT_INSTALL: {
12491                        // Revoke this as runtime permission to handle the case of
12492                        // a runtime permission being downgraded to an install one.
12493                        // Also in permission review mode we keep dangerous permissions
12494                        // for legacy apps
12495                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12496                            if (origPermissions.getRuntimePermissionState(
12497                                    bp.name, userId) != null) {
12498                                // Revoke the runtime permission and clear the flags.
12499                                origPermissions.revokeRuntimePermission(bp, userId);
12500                                origPermissions.updatePermissionFlags(bp, userId,
12501                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
12502                                // If we revoked a permission permission, we have to write.
12503                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12504                                        changedRuntimePermissionUserIds, userId);
12505                            }
12506                        }
12507                        // Grant an install permission.
12508                        if (permissionsState.grantInstallPermission(bp) !=
12509                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
12510                            changedInstallPermission = true;
12511                        }
12512                    } break;
12513
12514                    case GRANT_RUNTIME: {
12515                        // Grant previously granted runtime permissions.
12516                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12517                            PermissionState permissionState = origPermissions
12518                                    .getRuntimePermissionState(bp.name, userId);
12519                            int flags = permissionState != null
12520                                    ? permissionState.getFlags() : 0;
12521                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
12522                                // Don't propagate the permission in a permission review mode if
12523                                // the former was revoked, i.e. marked to not propagate on upgrade.
12524                                // Note that in a permission review mode install permissions are
12525                                // represented as constantly granted runtime ones since we need to
12526                                // keep a per user state associated with the permission. Also the
12527                                // revoke on upgrade flag is no longer applicable and is reset.
12528                                final boolean revokeOnUpgrade = (flags & PackageManager
12529                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
12530                                if (revokeOnUpgrade) {
12531                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
12532                                    // Since we changed the flags, we have to write.
12533                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12534                                            changedRuntimePermissionUserIds, userId);
12535                                }
12536                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
12537                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
12538                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
12539                                        // If we cannot put the permission as it was,
12540                                        // we have to write.
12541                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12542                                                changedRuntimePermissionUserIds, userId);
12543                                    }
12544                                }
12545
12546                                // If the app supports runtime permissions no need for a review.
12547                                if (mPermissionReviewRequired
12548                                        && appSupportsRuntimePermissions
12549                                        && (flags & PackageManager
12550                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
12551                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
12552                                    // Since we changed the flags, we have to write.
12553                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12554                                            changedRuntimePermissionUserIds, userId);
12555                                }
12556                            } else if (mPermissionReviewRequired
12557                                    && !appSupportsRuntimePermissions) {
12558                                // For legacy apps that need a permission review, every new
12559                                // runtime permission is granted but it is pending a review.
12560                                // We also need to review only platform defined runtime
12561                                // permissions as these are the only ones the platform knows
12562                                // how to disable the API to simulate revocation as legacy
12563                                // apps don't expect to run with revoked permissions.
12564                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
12565                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
12566                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
12567                                        // We changed the flags, hence have to write.
12568                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12569                                                changedRuntimePermissionUserIds, userId);
12570                                    }
12571                                }
12572                                if (permissionsState.grantRuntimePermission(bp, userId)
12573                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
12574                                    // We changed the permission, hence have to write.
12575                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12576                                            changedRuntimePermissionUserIds, userId);
12577                                }
12578                            }
12579                            // Propagate the permission flags.
12580                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
12581                        }
12582                    } break;
12583
12584                    case GRANT_UPGRADE: {
12585                        // Grant runtime permissions for a previously held install permission.
12586                        PermissionState permissionState = origPermissions
12587                                .getInstallPermissionState(bp.name);
12588                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
12589
12590                        if (origPermissions.revokeInstallPermission(bp)
12591                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
12592                            // We will be transferring the permission flags, so clear them.
12593                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
12594                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
12595                            changedInstallPermission = true;
12596                        }
12597
12598                        // If the permission is not to be promoted to runtime we ignore it and
12599                        // also its other flags as they are not applicable to install permissions.
12600                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
12601                            for (int userId : currentUserIds) {
12602                                if (permissionsState.grantRuntimePermission(bp, userId) !=
12603                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
12604                                    // Transfer the permission flags.
12605                                    permissionsState.updatePermissionFlags(bp, userId,
12606                                            flags, flags);
12607                                    // If we granted the permission, we have to write.
12608                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12609                                            changedRuntimePermissionUserIds, userId);
12610                                }
12611                            }
12612                        }
12613                    } break;
12614
12615                    default: {
12616                        if (packageOfInterest == null
12617                                || packageOfInterest.equals(pkg.packageName)) {
12618                            if (DEBUG_PERMISSIONS) {
12619                                Slog.i(TAG, "Not granting permission " + perm
12620                                        + " to package " + pkg.packageName
12621                                        + " because it was previously installed without");
12622                            }
12623                        }
12624                    } break;
12625                }
12626            } else {
12627                if (permissionsState.revokeInstallPermission(bp) !=
12628                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
12629                    // Also drop the permission flags.
12630                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
12631                            PackageManager.MASK_PERMISSION_FLAGS, 0);
12632                    changedInstallPermission = true;
12633                    Slog.i(TAG, "Un-granting permission " + perm
12634                            + " from package " + pkg.packageName
12635                            + " (protectionLevel=" + bp.protectionLevel
12636                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
12637                            + ")");
12638                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
12639                    // Don't print warning for app op permissions, since it is fine for them
12640                    // not to be granted, there is a UI for the user to decide.
12641                    if (DEBUG_PERMISSIONS
12642                            && (packageOfInterest == null
12643                                    || packageOfInterest.equals(pkg.packageName))) {
12644                        Slog.i(TAG, "Not granting permission " + perm
12645                                + " to package " + pkg.packageName
12646                                + " (protectionLevel=" + bp.protectionLevel
12647                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
12648                                + ")");
12649                    }
12650                }
12651            }
12652        }
12653
12654        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
12655                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
12656            // This is the first that we have heard about this package, so the
12657            // permissions we have now selected are fixed until explicitly
12658            // changed.
12659            ps.installPermissionsFixed = true;
12660        }
12661
12662        // Persist the runtime permissions state for users with changes. If permissions
12663        // were revoked because no app in the shared user declares them we have to
12664        // write synchronously to avoid losing runtime permissions state.
12665        for (int userId : changedRuntimePermissionUserIds) {
12666            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
12667        }
12668    }
12669
12670    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
12671        boolean allowed = false;
12672        final int NP = PackageParser.NEW_PERMISSIONS.length;
12673        for (int ip=0; ip<NP; ip++) {
12674            final PackageParser.NewPermissionInfo npi
12675                    = PackageParser.NEW_PERMISSIONS[ip];
12676            if (npi.name.equals(perm)
12677                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
12678                allowed = true;
12679                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
12680                        + pkg.packageName);
12681                break;
12682            }
12683        }
12684        return allowed;
12685    }
12686
12687    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
12688            BasePermission bp, PermissionsState origPermissions) {
12689        boolean privilegedPermission = (bp.protectionLevel
12690                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
12691        boolean privappPermissionsDisable =
12692                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
12693        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
12694        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
12695        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
12696                && !platformPackage && platformPermission) {
12697            ArraySet<String> wlPermissions = SystemConfig.getInstance()
12698                    .getPrivAppPermissions(pkg.packageName);
12699            boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
12700            if (!whitelisted) {
12701                Slog.w(TAG, "Privileged permission " + perm + " for package "
12702                        + pkg.packageName + " - not in privapp-permissions whitelist");
12703                // Only report violations for apps on system image
12704                if (!mSystemReady && !pkg.isUpdatedSystemApp()) {
12705                    if (mPrivappPermissionsViolations == null) {
12706                        mPrivappPermissionsViolations = new ArraySet<>();
12707                    }
12708                    mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
12709                }
12710                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
12711                    return false;
12712                }
12713            }
12714        }
12715        boolean allowed = (compareSignatures(
12716                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
12717                        == PackageManager.SIGNATURE_MATCH)
12718                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
12719                        == PackageManager.SIGNATURE_MATCH);
12720        if (!allowed && privilegedPermission) {
12721            if (isSystemApp(pkg)) {
12722                // For updated system applications, a system permission
12723                // is granted only if it had been defined by the original application.
12724                if (pkg.isUpdatedSystemApp()) {
12725                    final PackageSetting sysPs = mSettings
12726                            .getDisabledSystemPkgLPr(pkg.packageName);
12727                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
12728                        // If the original was granted this permission, we take
12729                        // that grant decision as read and propagate it to the
12730                        // update.
12731                        if (sysPs.isPrivileged()) {
12732                            allowed = true;
12733                        }
12734                    } else {
12735                        // The system apk may have been updated with an older
12736                        // version of the one on the data partition, but which
12737                        // granted a new system permission that it didn't have
12738                        // before.  In this case we do want to allow the app to
12739                        // now get the new permission if the ancestral apk is
12740                        // privileged to get it.
12741                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
12742                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
12743                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
12744                                    allowed = true;
12745                                    break;
12746                                }
12747                            }
12748                        }
12749                        // Also if a privileged parent package on the system image or any of
12750                        // its children requested a privileged permission, the updated child
12751                        // packages can also get the permission.
12752                        if (pkg.parentPackage != null) {
12753                            final PackageSetting disabledSysParentPs = mSettings
12754                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
12755                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
12756                                    && disabledSysParentPs.isPrivileged()) {
12757                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
12758                                    allowed = true;
12759                                } else if (disabledSysParentPs.pkg.childPackages != null) {
12760                                    final int count = disabledSysParentPs.pkg.childPackages.size();
12761                                    for (int i = 0; i < count; i++) {
12762                                        PackageParser.Package disabledSysChildPkg =
12763                                                disabledSysParentPs.pkg.childPackages.get(i);
12764                                        if (isPackageRequestingPermission(disabledSysChildPkg,
12765                                                perm)) {
12766                                            allowed = true;
12767                                            break;
12768                                        }
12769                                    }
12770                                }
12771                            }
12772                        }
12773                    }
12774                } else {
12775                    allowed = isPrivilegedApp(pkg);
12776                }
12777            }
12778        }
12779        if (!allowed) {
12780            if (!allowed && (bp.protectionLevel
12781                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
12782                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
12783                // If this was a previously normal/dangerous permission that got moved
12784                // to a system permission as part of the runtime permission redesign, then
12785                // we still want to blindly grant it to old apps.
12786                allowed = true;
12787            }
12788            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
12789                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
12790                // If this permission is to be granted to the system installer and
12791                // this app is an installer, then it gets the permission.
12792                allowed = true;
12793            }
12794            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
12795                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
12796                // If this permission is to be granted to the system verifier and
12797                // this app is a verifier, then it gets the permission.
12798                allowed = true;
12799            }
12800            if (!allowed && (bp.protectionLevel
12801                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
12802                    && isSystemApp(pkg)) {
12803                // Any pre-installed system app is allowed to get this permission.
12804                allowed = true;
12805            }
12806            if (!allowed && (bp.protectionLevel
12807                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
12808                // For development permissions, a development permission
12809                // is granted only if it was already granted.
12810                allowed = origPermissions.hasInstallPermission(perm);
12811            }
12812            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
12813                    && pkg.packageName.equals(mSetupWizardPackage)) {
12814                // If this permission is to be granted to the system setup wizard and
12815                // this app is a setup wizard, then it gets the permission.
12816                allowed = true;
12817            }
12818        }
12819        return allowed;
12820    }
12821
12822    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
12823        final int permCount = pkg.requestedPermissions.size();
12824        for (int j = 0; j < permCount; j++) {
12825            String requestedPermission = pkg.requestedPermissions.get(j);
12826            if (permission.equals(requestedPermission)) {
12827                return true;
12828            }
12829        }
12830        return false;
12831    }
12832
12833    final class ActivityIntentResolver
12834            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
12835        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12836                boolean defaultOnly, int userId) {
12837            if (!sUserManager.exists(userId)) return null;
12838            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
12839            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12840        }
12841
12842        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12843                int userId) {
12844            if (!sUserManager.exists(userId)) return null;
12845            mFlags = flags;
12846            return super.queryIntent(intent, resolvedType,
12847                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12848                    userId);
12849        }
12850
12851        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12852                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
12853            if (!sUserManager.exists(userId)) return null;
12854            if (packageActivities == null) {
12855                return null;
12856            }
12857            mFlags = flags;
12858            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12859            final int N = packageActivities.size();
12860            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
12861                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
12862
12863            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
12864            for (int i = 0; i < N; ++i) {
12865                intentFilters = packageActivities.get(i).intents;
12866                if (intentFilters != null && intentFilters.size() > 0) {
12867                    PackageParser.ActivityIntentInfo[] array =
12868                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
12869                    intentFilters.toArray(array);
12870                    listCut.add(array);
12871                }
12872            }
12873            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12874        }
12875
12876        /**
12877         * Finds a privileged activity that matches the specified activity names.
12878         */
12879        private PackageParser.Activity findMatchingActivity(
12880                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
12881            for (PackageParser.Activity sysActivity : activityList) {
12882                if (sysActivity.info.name.equals(activityInfo.name)) {
12883                    return sysActivity;
12884                }
12885                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
12886                    return sysActivity;
12887                }
12888                if (sysActivity.info.targetActivity != null) {
12889                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
12890                        return sysActivity;
12891                    }
12892                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
12893                        return sysActivity;
12894                    }
12895                }
12896            }
12897            return null;
12898        }
12899
12900        public class IterGenerator<E> {
12901            public Iterator<E> generate(ActivityIntentInfo info) {
12902                return null;
12903            }
12904        }
12905
12906        public class ActionIterGenerator extends IterGenerator<String> {
12907            @Override
12908            public Iterator<String> generate(ActivityIntentInfo info) {
12909                return info.actionsIterator();
12910            }
12911        }
12912
12913        public class CategoriesIterGenerator extends IterGenerator<String> {
12914            @Override
12915            public Iterator<String> generate(ActivityIntentInfo info) {
12916                return info.categoriesIterator();
12917            }
12918        }
12919
12920        public class SchemesIterGenerator extends IterGenerator<String> {
12921            @Override
12922            public Iterator<String> generate(ActivityIntentInfo info) {
12923                return info.schemesIterator();
12924            }
12925        }
12926
12927        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
12928            @Override
12929            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
12930                return info.authoritiesIterator();
12931            }
12932        }
12933
12934        /**
12935         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
12936         * MODIFIED. Do not pass in a list that should not be changed.
12937         */
12938        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
12939                IterGenerator<T> generator, Iterator<T> searchIterator) {
12940            // loop through the set of actions; every one must be found in the intent filter
12941            while (searchIterator.hasNext()) {
12942                // we must have at least one filter in the list to consider a match
12943                if (intentList.size() == 0) {
12944                    break;
12945                }
12946
12947                final T searchAction = searchIterator.next();
12948
12949                // loop through the set of intent filters
12950                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
12951                while (intentIter.hasNext()) {
12952                    final ActivityIntentInfo intentInfo = intentIter.next();
12953                    boolean selectionFound = false;
12954
12955                    // loop through the intent filter's selection criteria; at least one
12956                    // of them must match the searched criteria
12957                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
12958                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
12959                        final T intentSelection = intentSelectionIter.next();
12960                        if (intentSelection != null && intentSelection.equals(searchAction)) {
12961                            selectionFound = true;
12962                            break;
12963                        }
12964                    }
12965
12966                    // the selection criteria wasn't found in this filter's set; this filter
12967                    // is not a potential match
12968                    if (!selectionFound) {
12969                        intentIter.remove();
12970                    }
12971                }
12972            }
12973        }
12974
12975        private boolean isProtectedAction(ActivityIntentInfo filter) {
12976            final Iterator<String> actionsIter = filter.actionsIterator();
12977            while (actionsIter != null && actionsIter.hasNext()) {
12978                final String filterAction = actionsIter.next();
12979                if (PROTECTED_ACTIONS.contains(filterAction)) {
12980                    return true;
12981                }
12982            }
12983            return false;
12984        }
12985
12986        /**
12987         * Adjusts the priority of the given intent filter according to policy.
12988         * <p>
12989         * <ul>
12990         * <li>The priority for non privileged applications is capped to '0'</li>
12991         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
12992         * <li>The priority for unbundled updates to privileged applications is capped to the
12993         *      priority defined on the system partition</li>
12994         * </ul>
12995         * <p>
12996         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
12997         * allowed to obtain any priority on any action.
12998         */
12999        private void adjustPriority(
13000                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
13001            // nothing to do; priority is fine as-is
13002            if (intent.getPriority() <= 0) {
13003                return;
13004            }
13005
13006            final ActivityInfo activityInfo = intent.activity.info;
13007            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
13008
13009            final boolean privilegedApp =
13010                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
13011            if (!privilegedApp) {
13012                // non-privileged applications can never define a priority >0
13013                if (DEBUG_FILTERS) {
13014                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
13015                            + " package: " + applicationInfo.packageName
13016                            + " activity: " + intent.activity.className
13017                            + " origPrio: " + intent.getPriority());
13018                }
13019                intent.setPriority(0);
13020                return;
13021            }
13022
13023            if (systemActivities == null) {
13024                // the system package is not disabled; we're parsing the system partition
13025                if (isProtectedAction(intent)) {
13026                    if (mDeferProtectedFilters) {
13027                        // We can't deal with these just yet. No component should ever obtain a
13028                        // >0 priority for a protected actions, with ONE exception -- the setup
13029                        // wizard. The setup wizard, however, cannot be known until we're able to
13030                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
13031                        // until all intent filters have been processed. Chicken, meet egg.
13032                        // Let the filter temporarily have a high priority and rectify the
13033                        // priorities after all system packages have been scanned.
13034                        mProtectedFilters.add(intent);
13035                        if (DEBUG_FILTERS) {
13036                            Slog.i(TAG, "Protected action; save for later;"
13037                                    + " package: " + applicationInfo.packageName
13038                                    + " activity: " + intent.activity.className
13039                                    + " origPrio: " + intent.getPriority());
13040                        }
13041                        return;
13042                    } else {
13043                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
13044                            Slog.i(TAG, "No setup wizard;"
13045                                + " All protected intents capped to priority 0");
13046                        }
13047                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
13048                            if (DEBUG_FILTERS) {
13049                                Slog.i(TAG, "Found setup wizard;"
13050                                    + " allow priority " + intent.getPriority() + ";"
13051                                    + " package: " + intent.activity.info.packageName
13052                                    + " activity: " + intent.activity.className
13053                                    + " priority: " + intent.getPriority());
13054                            }
13055                            // setup wizard gets whatever it wants
13056                            return;
13057                        }
13058                        if (DEBUG_FILTERS) {
13059                            Slog.i(TAG, "Protected action; cap priority to 0;"
13060                                    + " package: " + intent.activity.info.packageName
13061                                    + " activity: " + intent.activity.className
13062                                    + " origPrio: " + intent.getPriority());
13063                        }
13064                        intent.setPriority(0);
13065                        return;
13066                    }
13067                }
13068                // privileged apps on the system image get whatever priority they request
13069                return;
13070            }
13071
13072            // privileged app unbundled update ... try to find the same activity
13073            final PackageParser.Activity foundActivity =
13074                    findMatchingActivity(systemActivities, activityInfo);
13075            if (foundActivity == null) {
13076                // this is a new activity; it cannot obtain >0 priority
13077                if (DEBUG_FILTERS) {
13078                    Slog.i(TAG, "New activity; cap priority to 0;"
13079                            + " package: " + applicationInfo.packageName
13080                            + " activity: " + intent.activity.className
13081                            + " origPrio: " + intent.getPriority());
13082                }
13083                intent.setPriority(0);
13084                return;
13085            }
13086
13087            // found activity, now check for filter equivalence
13088
13089            // a shallow copy is enough; we modify the list, not its contents
13090            final List<ActivityIntentInfo> intentListCopy =
13091                    new ArrayList<>(foundActivity.intents);
13092            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
13093
13094            // find matching action subsets
13095            final Iterator<String> actionsIterator = intent.actionsIterator();
13096            if (actionsIterator != null) {
13097                getIntentListSubset(
13098                        intentListCopy, new ActionIterGenerator(), actionsIterator);
13099                if (intentListCopy.size() == 0) {
13100                    // no more intents to match; we're not equivalent
13101                    if (DEBUG_FILTERS) {
13102                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
13103                                + " package: " + applicationInfo.packageName
13104                                + " activity: " + intent.activity.className
13105                                + " origPrio: " + intent.getPriority());
13106                    }
13107                    intent.setPriority(0);
13108                    return;
13109                }
13110            }
13111
13112            // find matching category subsets
13113            final Iterator<String> categoriesIterator = intent.categoriesIterator();
13114            if (categoriesIterator != null) {
13115                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
13116                        categoriesIterator);
13117                if (intentListCopy.size() == 0) {
13118                    // no more intents to match; we're not equivalent
13119                    if (DEBUG_FILTERS) {
13120                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
13121                                + " package: " + applicationInfo.packageName
13122                                + " activity: " + intent.activity.className
13123                                + " origPrio: " + intent.getPriority());
13124                    }
13125                    intent.setPriority(0);
13126                    return;
13127                }
13128            }
13129
13130            // find matching schemes subsets
13131            final Iterator<String> schemesIterator = intent.schemesIterator();
13132            if (schemesIterator != null) {
13133                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
13134                        schemesIterator);
13135                if (intentListCopy.size() == 0) {
13136                    // no more intents to match; we're not equivalent
13137                    if (DEBUG_FILTERS) {
13138                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
13139                                + " package: " + applicationInfo.packageName
13140                                + " activity: " + intent.activity.className
13141                                + " origPrio: " + intent.getPriority());
13142                    }
13143                    intent.setPriority(0);
13144                    return;
13145                }
13146            }
13147
13148            // find matching authorities subsets
13149            final Iterator<IntentFilter.AuthorityEntry>
13150                    authoritiesIterator = intent.authoritiesIterator();
13151            if (authoritiesIterator != null) {
13152                getIntentListSubset(intentListCopy,
13153                        new AuthoritiesIterGenerator(),
13154                        authoritiesIterator);
13155                if (intentListCopy.size() == 0) {
13156                    // no more intents to match; we're not equivalent
13157                    if (DEBUG_FILTERS) {
13158                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
13159                                + " package: " + applicationInfo.packageName
13160                                + " activity: " + intent.activity.className
13161                                + " origPrio: " + intent.getPriority());
13162                    }
13163                    intent.setPriority(0);
13164                    return;
13165                }
13166            }
13167
13168            // we found matching filter(s); app gets the max priority of all intents
13169            int cappedPriority = 0;
13170            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
13171                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
13172            }
13173            if (intent.getPriority() > cappedPriority) {
13174                if (DEBUG_FILTERS) {
13175                    Slog.i(TAG, "Found matching filter(s);"
13176                            + " cap priority to " + cappedPriority + ";"
13177                            + " package: " + applicationInfo.packageName
13178                            + " activity: " + intent.activity.className
13179                            + " origPrio: " + intent.getPriority());
13180                }
13181                intent.setPriority(cappedPriority);
13182                return;
13183            }
13184            // all this for nothing; the requested priority was <= what was on the system
13185        }
13186
13187        public final void addActivity(PackageParser.Activity a, String type) {
13188            mActivities.put(a.getComponentName(), a);
13189            if (DEBUG_SHOW_INFO)
13190                Log.v(
13191                TAG, "  " + type + " " +
13192                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
13193            if (DEBUG_SHOW_INFO)
13194                Log.v(TAG, "    Class=" + a.info.name);
13195            final int NI = a.intents.size();
13196            for (int j=0; j<NI; j++) {
13197                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13198                if ("activity".equals(type)) {
13199                    final PackageSetting ps =
13200                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
13201                    final List<PackageParser.Activity> systemActivities =
13202                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
13203                    adjustPriority(systemActivities, intent);
13204                }
13205                if (DEBUG_SHOW_INFO) {
13206                    Log.v(TAG, "    IntentFilter:");
13207                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13208                }
13209                if (!intent.debugCheck()) {
13210                    Log.w(TAG, "==> For Activity " + a.info.name);
13211                }
13212                addFilter(intent);
13213            }
13214        }
13215
13216        public final void removeActivity(PackageParser.Activity a, String type) {
13217            mActivities.remove(a.getComponentName());
13218            if (DEBUG_SHOW_INFO) {
13219                Log.v(TAG, "  " + type + " "
13220                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
13221                                : a.info.name) + ":");
13222                Log.v(TAG, "    Class=" + a.info.name);
13223            }
13224            final int NI = a.intents.size();
13225            for (int j=0; j<NI; j++) {
13226                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13227                if (DEBUG_SHOW_INFO) {
13228                    Log.v(TAG, "    IntentFilter:");
13229                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13230                }
13231                removeFilter(intent);
13232            }
13233        }
13234
13235        @Override
13236        protected boolean allowFilterResult(
13237                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
13238            ActivityInfo filterAi = filter.activity.info;
13239            for (int i=dest.size()-1; i>=0; i--) {
13240                ActivityInfo destAi = dest.get(i).activityInfo;
13241                if (destAi.name == filterAi.name
13242                        && destAi.packageName == filterAi.packageName) {
13243                    return false;
13244                }
13245            }
13246            return true;
13247        }
13248
13249        @Override
13250        protected ActivityIntentInfo[] newArray(int size) {
13251            return new ActivityIntentInfo[size];
13252        }
13253
13254        @Override
13255        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
13256            if (!sUserManager.exists(userId)) return true;
13257            PackageParser.Package p = filter.activity.owner;
13258            if (p != null) {
13259                PackageSetting ps = (PackageSetting)p.mExtras;
13260                if (ps != null) {
13261                    // System apps are never considered stopped for purposes of
13262                    // filtering, because there may be no way for the user to
13263                    // actually re-launch them.
13264                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
13265                            && ps.getStopped(userId);
13266                }
13267            }
13268            return false;
13269        }
13270
13271        @Override
13272        protected boolean isPackageForFilter(String packageName,
13273                PackageParser.ActivityIntentInfo info) {
13274            return packageName.equals(info.activity.owner.packageName);
13275        }
13276
13277        @Override
13278        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
13279                int match, int userId) {
13280            if (!sUserManager.exists(userId)) return null;
13281            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
13282                return null;
13283            }
13284            final PackageParser.Activity activity = info.activity;
13285            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
13286            if (ps == null) {
13287                return null;
13288            }
13289            final PackageUserState userState = ps.readUserState(userId);
13290            ActivityInfo ai =
13291                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
13292            if (ai == null) {
13293                return null;
13294            }
13295            final boolean matchExplicitlyVisibleOnly =
13296                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
13297            final boolean matchVisibleToInstantApp =
13298                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13299            final boolean componentVisible =
13300                    matchVisibleToInstantApp
13301                    && info.isVisibleToInstantApp()
13302                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
13303            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13304            // throw out filters that aren't visible to ephemeral apps
13305            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
13306                return null;
13307            }
13308            // throw out instant app filters if we're not explicitly requesting them
13309            if (!matchInstantApp && userState.instantApp) {
13310                return null;
13311            }
13312            // throw out instant app filters if updates are available; will trigger
13313            // instant app resolution
13314            if (userState.instantApp && ps.isUpdateAvailable()) {
13315                return null;
13316            }
13317            final ResolveInfo res = new ResolveInfo();
13318            res.activityInfo = ai;
13319            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13320                res.filter = info;
13321            }
13322            if (info != null) {
13323                res.handleAllWebDataURI = info.handleAllWebDataURI();
13324            }
13325            res.priority = info.getPriority();
13326            res.preferredOrder = activity.owner.mPreferredOrder;
13327            //System.out.println("Result: " + res.activityInfo.className +
13328            //                   " = " + res.priority);
13329            res.match = match;
13330            res.isDefault = info.hasDefault;
13331            res.labelRes = info.labelRes;
13332            res.nonLocalizedLabel = info.nonLocalizedLabel;
13333            if (userNeedsBadging(userId)) {
13334                res.noResourceId = true;
13335            } else {
13336                res.icon = info.icon;
13337            }
13338            res.iconResourceId = info.icon;
13339            res.system = res.activityInfo.applicationInfo.isSystemApp();
13340            res.isInstantAppAvailable = userState.instantApp;
13341            return res;
13342        }
13343
13344        @Override
13345        protected void sortResults(List<ResolveInfo> results) {
13346            Collections.sort(results, mResolvePrioritySorter);
13347        }
13348
13349        @Override
13350        protected void dumpFilter(PrintWriter out, String prefix,
13351                PackageParser.ActivityIntentInfo filter) {
13352            out.print(prefix); out.print(
13353                    Integer.toHexString(System.identityHashCode(filter.activity)));
13354                    out.print(' ');
13355                    filter.activity.printComponentShortName(out);
13356                    out.print(" filter ");
13357                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13358        }
13359
13360        @Override
13361        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
13362            return filter.activity;
13363        }
13364
13365        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13366            PackageParser.Activity activity = (PackageParser.Activity)label;
13367            out.print(prefix); out.print(
13368                    Integer.toHexString(System.identityHashCode(activity)));
13369                    out.print(' ');
13370                    activity.printComponentShortName(out);
13371            if (count > 1) {
13372                out.print(" ("); out.print(count); out.print(" filters)");
13373            }
13374            out.println();
13375        }
13376
13377        // Keys are String (activity class name), values are Activity.
13378        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
13379                = new ArrayMap<ComponentName, PackageParser.Activity>();
13380        private int mFlags;
13381    }
13382
13383    private final class ServiceIntentResolver
13384            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
13385        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13386                boolean defaultOnly, int userId) {
13387            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13388            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13389        }
13390
13391        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13392                int userId) {
13393            if (!sUserManager.exists(userId)) return null;
13394            mFlags = flags;
13395            return super.queryIntent(intent, resolvedType,
13396                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13397                    userId);
13398        }
13399
13400        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13401                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
13402            if (!sUserManager.exists(userId)) return null;
13403            if (packageServices == null) {
13404                return null;
13405            }
13406            mFlags = flags;
13407            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
13408            final int N = packageServices.size();
13409            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
13410                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
13411
13412            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
13413            for (int i = 0; i < N; ++i) {
13414                intentFilters = packageServices.get(i).intents;
13415                if (intentFilters != null && intentFilters.size() > 0) {
13416                    PackageParser.ServiceIntentInfo[] array =
13417                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
13418                    intentFilters.toArray(array);
13419                    listCut.add(array);
13420                }
13421            }
13422            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13423        }
13424
13425        public final void addService(PackageParser.Service s) {
13426            mServices.put(s.getComponentName(), s);
13427            if (DEBUG_SHOW_INFO) {
13428                Log.v(TAG, "  "
13429                        + (s.info.nonLocalizedLabel != null
13430                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13431                Log.v(TAG, "    Class=" + s.info.name);
13432            }
13433            final int NI = s.intents.size();
13434            int j;
13435            for (j=0; j<NI; j++) {
13436                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13437                if (DEBUG_SHOW_INFO) {
13438                    Log.v(TAG, "    IntentFilter:");
13439                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13440                }
13441                if (!intent.debugCheck()) {
13442                    Log.w(TAG, "==> For Service " + s.info.name);
13443                }
13444                addFilter(intent);
13445            }
13446        }
13447
13448        public final void removeService(PackageParser.Service s) {
13449            mServices.remove(s.getComponentName());
13450            if (DEBUG_SHOW_INFO) {
13451                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
13452                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13453                Log.v(TAG, "    Class=" + s.info.name);
13454            }
13455            final int NI = s.intents.size();
13456            int j;
13457            for (j=0; j<NI; j++) {
13458                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13459                if (DEBUG_SHOW_INFO) {
13460                    Log.v(TAG, "    IntentFilter:");
13461                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13462                }
13463                removeFilter(intent);
13464            }
13465        }
13466
13467        @Override
13468        protected boolean allowFilterResult(
13469                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
13470            ServiceInfo filterSi = filter.service.info;
13471            for (int i=dest.size()-1; i>=0; i--) {
13472                ServiceInfo destAi = dest.get(i).serviceInfo;
13473                if (destAi.name == filterSi.name
13474                        && destAi.packageName == filterSi.packageName) {
13475                    return false;
13476                }
13477            }
13478            return true;
13479        }
13480
13481        @Override
13482        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
13483            return new PackageParser.ServiceIntentInfo[size];
13484        }
13485
13486        @Override
13487        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
13488            if (!sUserManager.exists(userId)) return true;
13489            PackageParser.Package p = filter.service.owner;
13490            if (p != null) {
13491                PackageSetting ps = (PackageSetting)p.mExtras;
13492                if (ps != null) {
13493                    // System apps are never considered stopped for purposes of
13494                    // filtering, because there may be no way for the user to
13495                    // actually re-launch them.
13496                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13497                            && ps.getStopped(userId);
13498                }
13499            }
13500            return false;
13501        }
13502
13503        @Override
13504        protected boolean isPackageForFilter(String packageName,
13505                PackageParser.ServiceIntentInfo info) {
13506            return packageName.equals(info.service.owner.packageName);
13507        }
13508
13509        @Override
13510        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
13511                int match, int userId) {
13512            if (!sUserManager.exists(userId)) return null;
13513            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
13514            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
13515                return null;
13516            }
13517            final PackageParser.Service service = info.service;
13518            PackageSetting ps = (PackageSetting) service.owner.mExtras;
13519            if (ps == null) {
13520                return null;
13521            }
13522            final PackageUserState userState = ps.readUserState(userId);
13523            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
13524                    userState, userId);
13525            if (si == null) {
13526                return null;
13527            }
13528            final boolean matchVisibleToInstantApp =
13529                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13530            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13531            // throw out filters that aren't visible to ephemeral apps
13532            if (matchVisibleToInstantApp
13533                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13534                return null;
13535            }
13536            // throw out ephemeral filters if we're not explicitly requesting them
13537            if (!isInstantApp && userState.instantApp) {
13538                return null;
13539            }
13540            // throw out instant app filters if updates are available; will trigger
13541            // instant app resolution
13542            if (userState.instantApp && ps.isUpdateAvailable()) {
13543                return null;
13544            }
13545            final ResolveInfo res = new ResolveInfo();
13546            res.serviceInfo = si;
13547            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13548                res.filter = filter;
13549            }
13550            res.priority = info.getPriority();
13551            res.preferredOrder = service.owner.mPreferredOrder;
13552            res.match = match;
13553            res.isDefault = info.hasDefault;
13554            res.labelRes = info.labelRes;
13555            res.nonLocalizedLabel = info.nonLocalizedLabel;
13556            res.icon = info.icon;
13557            res.system = res.serviceInfo.applicationInfo.isSystemApp();
13558            return res;
13559        }
13560
13561        @Override
13562        protected void sortResults(List<ResolveInfo> results) {
13563            Collections.sort(results, mResolvePrioritySorter);
13564        }
13565
13566        @Override
13567        protected void dumpFilter(PrintWriter out, String prefix,
13568                PackageParser.ServiceIntentInfo filter) {
13569            out.print(prefix); out.print(
13570                    Integer.toHexString(System.identityHashCode(filter.service)));
13571                    out.print(' ');
13572                    filter.service.printComponentShortName(out);
13573                    out.print(" filter ");
13574                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13575        }
13576
13577        @Override
13578        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
13579            return filter.service;
13580        }
13581
13582        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13583            PackageParser.Service service = (PackageParser.Service)label;
13584            out.print(prefix); out.print(
13585                    Integer.toHexString(System.identityHashCode(service)));
13586                    out.print(' ');
13587                    service.printComponentShortName(out);
13588            if (count > 1) {
13589                out.print(" ("); out.print(count); out.print(" filters)");
13590            }
13591            out.println();
13592        }
13593
13594//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
13595//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
13596//            final List<ResolveInfo> retList = Lists.newArrayList();
13597//            while (i.hasNext()) {
13598//                final ResolveInfo resolveInfo = (ResolveInfo) i;
13599//                if (isEnabledLP(resolveInfo.serviceInfo)) {
13600//                    retList.add(resolveInfo);
13601//                }
13602//            }
13603//            return retList;
13604//        }
13605
13606        // Keys are String (activity class name), values are Activity.
13607        private final ArrayMap<ComponentName, PackageParser.Service> mServices
13608                = new ArrayMap<ComponentName, PackageParser.Service>();
13609        private int mFlags;
13610    }
13611
13612    private final class ProviderIntentResolver
13613            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
13614        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13615                boolean defaultOnly, int userId) {
13616            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13617            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13618        }
13619
13620        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13621                int userId) {
13622            if (!sUserManager.exists(userId))
13623                return null;
13624            mFlags = flags;
13625            return super.queryIntent(intent, resolvedType,
13626                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13627                    userId);
13628        }
13629
13630        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13631                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
13632            if (!sUserManager.exists(userId))
13633                return null;
13634            if (packageProviders == null) {
13635                return null;
13636            }
13637            mFlags = flags;
13638            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
13639            final int N = packageProviders.size();
13640            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
13641                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
13642
13643            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
13644            for (int i = 0; i < N; ++i) {
13645                intentFilters = packageProviders.get(i).intents;
13646                if (intentFilters != null && intentFilters.size() > 0) {
13647                    PackageParser.ProviderIntentInfo[] array =
13648                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
13649                    intentFilters.toArray(array);
13650                    listCut.add(array);
13651                }
13652            }
13653            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13654        }
13655
13656        public final void addProvider(PackageParser.Provider p) {
13657            if (mProviders.containsKey(p.getComponentName())) {
13658                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
13659                return;
13660            }
13661
13662            mProviders.put(p.getComponentName(), p);
13663            if (DEBUG_SHOW_INFO) {
13664                Log.v(TAG, "  "
13665                        + (p.info.nonLocalizedLabel != null
13666                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
13667                Log.v(TAG, "    Class=" + p.info.name);
13668            }
13669            final int NI = p.intents.size();
13670            int j;
13671            for (j = 0; j < NI; j++) {
13672                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13673                if (DEBUG_SHOW_INFO) {
13674                    Log.v(TAG, "    IntentFilter:");
13675                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13676                }
13677                if (!intent.debugCheck()) {
13678                    Log.w(TAG, "==> For Provider " + p.info.name);
13679                }
13680                addFilter(intent);
13681            }
13682        }
13683
13684        public final void removeProvider(PackageParser.Provider p) {
13685            mProviders.remove(p.getComponentName());
13686            if (DEBUG_SHOW_INFO) {
13687                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
13688                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
13689                Log.v(TAG, "    Class=" + p.info.name);
13690            }
13691            final int NI = p.intents.size();
13692            int j;
13693            for (j = 0; j < NI; j++) {
13694                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13695                if (DEBUG_SHOW_INFO) {
13696                    Log.v(TAG, "    IntentFilter:");
13697                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13698                }
13699                removeFilter(intent);
13700            }
13701        }
13702
13703        @Override
13704        protected boolean allowFilterResult(
13705                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
13706            ProviderInfo filterPi = filter.provider.info;
13707            for (int i = dest.size() - 1; i >= 0; i--) {
13708                ProviderInfo destPi = dest.get(i).providerInfo;
13709                if (destPi.name == filterPi.name
13710                        && destPi.packageName == filterPi.packageName) {
13711                    return false;
13712                }
13713            }
13714            return true;
13715        }
13716
13717        @Override
13718        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
13719            return new PackageParser.ProviderIntentInfo[size];
13720        }
13721
13722        @Override
13723        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
13724            if (!sUserManager.exists(userId))
13725                return true;
13726            PackageParser.Package p = filter.provider.owner;
13727            if (p != null) {
13728                PackageSetting ps = (PackageSetting) p.mExtras;
13729                if (ps != null) {
13730                    // System apps are never considered stopped for purposes of
13731                    // filtering, because there may be no way for the user to
13732                    // actually re-launch them.
13733                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13734                            && ps.getStopped(userId);
13735                }
13736            }
13737            return false;
13738        }
13739
13740        @Override
13741        protected boolean isPackageForFilter(String packageName,
13742                PackageParser.ProviderIntentInfo info) {
13743            return packageName.equals(info.provider.owner.packageName);
13744        }
13745
13746        @Override
13747        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
13748                int match, int userId) {
13749            if (!sUserManager.exists(userId))
13750                return null;
13751            final PackageParser.ProviderIntentInfo info = filter;
13752            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
13753                return null;
13754            }
13755            final PackageParser.Provider provider = info.provider;
13756            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
13757            if (ps == null) {
13758                return null;
13759            }
13760            final PackageUserState userState = ps.readUserState(userId);
13761            final boolean matchVisibleToInstantApp =
13762                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13763            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13764            // throw out filters that aren't visible to instant applications
13765            if (matchVisibleToInstantApp
13766                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13767                return null;
13768            }
13769            // throw out instant application filters if we're not explicitly requesting them
13770            if (!isInstantApp && userState.instantApp) {
13771                return null;
13772            }
13773            // throw out instant application filters if updates are available; will trigger
13774            // instant application resolution
13775            if (userState.instantApp && ps.isUpdateAvailable()) {
13776                return null;
13777            }
13778            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
13779                    userState, userId);
13780            if (pi == null) {
13781                return null;
13782            }
13783            final ResolveInfo res = new ResolveInfo();
13784            res.providerInfo = pi;
13785            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
13786                res.filter = filter;
13787            }
13788            res.priority = info.getPriority();
13789            res.preferredOrder = provider.owner.mPreferredOrder;
13790            res.match = match;
13791            res.isDefault = info.hasDefault;
13792            res.labelRes = info.labelRes;
13793            res.nonLocalizedLabel = info.nonLocalizedLabel;
13794            res.icon = info.icon;
13795            res.system = res.providerInfo.applicationInfo.isSystemApp();
13796            return res;
13797        }
13798
13799        @Override
13800        protected void sortResults(List<ResolveInfo> results) {
13801            Collections.sort(results, mResolvePrioritySorter);
13802        }
13803
13804        @Override
13805        protected void dumpFilter(PrintWriter out, String prefix,
13806                PackageParser.ProviderIntentInfo filter) {
13807            out.print(prefix);
13808            out.print(
13809                    Integer.toHexString(System.identityHashCode(filter.provider)));
13810            out.print(' ');
13811            filter.provider.printComponentShortName(out);
13812            out.print(" filter ");
13813            out.println(Integer.toHexString(System.identityHashCode(filter)));
13814        }
13815
13816        @Override
13817        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
13818            return filter.provider;
13819        }
13820
13821        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13822            PackageParser.Provider provider = (PackageParser.Provider)label;
13823            out.print(prefix); out.print(
13824                    Integer.toHexString(System.identityHashCode(provider)));
13825                    out.print(' ');
13826                    provider.printComponentShortName(out);
13827            if (count > 1) {
13828                out.print(" ("); out.print(count); out.print(" filters)");
13829            }
13830            out.println();
13831        }
13832
13833        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
13834                = new ArrayMap<ComponentName, PackageParser.Provider>();
13835        private int mFlags;
13836    }
13837
13838    static final class EphemeralIntentResolver
13839            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
13840        /**
13841         * The result that has the highest defined order. Ordering applies on a
13842         * per-package basis. Mapping is from package name to Pair of order and
13843         * EphemeralResolveInfo.
13844         * <p>
13845         * NOTE: This is implemented as a field variable for convenience and efficiency.
13846         * By having a field variable, we're able to track filter ordering as soon as
13847         * a non-zero order is defined. Otherwise, multiple loops across the result set
13848         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
13849         * this needs to be contained entirely within {@link #filterResults}.
13850         */
13851        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
13852
13853        @Override
13854        protected AuxiliaryResolveInfo[] newArray(int size) {
13855            return new AuxiliaryResolveInfo[size];
13856        }
13857
13858        @Override
13859        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
13860            return true;
13861        }
13862
13863        @Override
13864        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
13865                int userId) {
13866            if (!sUserManager.exists(userId)) {
13867                return null;
13868            }
13869            final String packageName = responseObj.resolveInfo.getPackageName();
13870            final Integer order = responseObj.getOrder();
13871            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
13872                    mOrderResult.get(packageName);
13873            // ordering is enabled and this item's order isn't high enough
13874            if (lastOrderResult != null && lastOrderResult.first >= order) {
13875                return null;
13876            }
13877            final InstantAppResolveInfo res = responseObj.resolveInfo;
13878            if (order > 0) {
13879                // non-zero order, enable ordering
13880                mOrderResult.put(packageName, new Pair<>(order, res));
13881            }
13882            return responseObj;
13883        }
13884
13885        @Override
13886        protected void filterResults(List<AuxiliaryResolveInfo> results) {
13887            // only do work if ordering is enabled [most of the time it won't be]
13888            if (mOrderResult.size() == 0) {
13889                return;
13890            }
13891            int resultSize = results.size();
13892            for (int i = 0; i < resultSize; i++) {
13893                final InstantAppResolveInfo info = results.get(i).resolveInfo;
13894                final String packageName = info.getPackageName();
13895                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
13896                if (savedInfo == null) {
13897                    // package doesn't having ordering
13898                    continue;
13899                }
13900                if (savedInfo.second == info) {
13901                    // circled back to the highest ordered item; remove from order list
13902                    mOrderResult.remove(savedInfo);
13903                    if (mOrderResult.size() == 0) {
13904                        // no more ordered items
13905                        break;
13906                    }
13907                    continue;
13908                }
13909                // item has a worse order, remove it from the result list
13910                results.remove(i);
13911                resultSize--;
13912                i--;
13913            }
13914        }
13915    }
13916
13917    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
13918            new Comparator<ResolveInfo>() {
13919        public int compare(ResolveInfo r1, ResolveInfo r2) {
13920            int v1 = r1.priority;
13921            int v2 = r2.priority;
13922            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
13923            if (v1 != v2) {
13924                return (v1 > v2) ? -1 : 1;
13925            }
13926            v1 = r1.preferredOrder;
13927            v2 = r2.preferredOrder;
13928            if (v1 != v2) {
13929                return (v1 > v2) ? -1 : 1;
13930            }
13931            if (r1.isDefault != r2.isDefault) {
13932                return r1.isDefault ? -1 : 1;
13933            }
13934            v1 = r1.match;
13935            v2 = r2.match;
13936            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
13937            if (v1 != v2) {
13938                return (v1 > v2) ? -1 : 1;
13939            }
13940            if (r1.system != r2.system) {
13941                return r1.system ? -1 : 1;
13942            }
13943            if (r1.activityInfo != null) {
13944                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
13945            }
13946            if (r1.serviceInfo != null) {
13947                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
13948            }
13949            if (r1.providerInfo != null) {
13950                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
13951            }
13952            return 0;
13953        }
13954    };
13955
13956    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
13957            new Comparator<ProviderInfo>() {
13958        public int compare(ProviderInfo p1, ProviderInfo p2) {
13959            final int v1 = p1.initOrder;
13960            final int v2 = p2.initOrder;
13961            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
13962        }
13963    };
13964
13965    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
13966            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
13967            final int[] userIds) {
13968        mHandler.post(new Runnable() {
13969            @Override
13970            public void run() {
13971                try {
13972                    final IActivityManager am = ActivityManager.getService();
13973                    if (am == null) return;
13974                    final int[] resolvedUserIds;
13975                    if (userIds == null) {
13976                        resolvedUserIds = am.getRunningUserIds();
13977                    } else {
13978                        resolvedUserIds = userIds;
13979                    }
13980                    for (int id : resolvedUserIds) {
13981                        final Intent intent = new Intent(action,
13982                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
13983                        if (extras != null) {
13984                            intent.putExtras(extras);
13985                        }
13986                        if (targetPkg != null) {
13987                            intent.setPackage(targetPkg);
13988                        }
13989                        // Modify the UID when posting to other users
13990                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
13991                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
13992                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
13993                            intent.putExtra(Intent.EXTRA_UID, uid);
13994                        }
13995                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
13996                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
13997                        if (DEBUG_BROADCASTS) {
13998                            RuntimeException here = new RuntimeException("here");
13999                            here.fillInStackTrace();
14000                            Slog.d(TAG, "Sending to user " + id + ": "
14001                                    + intent.toShortString(false, true, false, false)
14002                                    + " " + intent.getExtras(), here);
14003                        }
14004                        am.broadcastIntent(null, intent, null, finishedReceiver,
14005                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
14006                                null, finishedReceiver != null, false, id);
14007                    }
14008                } catch (RemoteException ex) {
14009                }
14010            }
14011        });
14012    }
14013
14014    /**
14015     * Check if the external storage media is available. This is true if there
14016     * is a mounted external storage medium or if the external storage is
14017     * emulated.
14018     */
14019    private boolean isExternalMediaAvailable() {
14020        return mMediaMounted || Environment.isExternalStorageEmulated();
14021    }
14022
14023    @Override
14024    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
14025        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14026            return null;
14027        }
14028        // writer
14029        synchronized (mPackages) {
14030            if (!isExternalMediaAvailable()) {
14031                // If the external storage is no longer mounted at this point,
14032                // the caller may not have been able to delete all of this
14033                // packages files and can not delete any more.  Bail.
14034                return null;
14035            }
14036            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
14037            if (lastPackage != null) {
14038                pkgs.remove(lastPackage);
14039            }
14040            if (pkgs.size() > 0) {
14041                return pkgs.get(0);
14042            }
14043        }
14044        return null;
14045    }
14046
14047    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
14048        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
14049                userId, andCode ? 1 : 0, packageName);
14050        if (mSystemReady) {
14051            msg.sendToTarget();
14052        } else {
14053            if (mPostSystemReadyMessages == null) {
14054                mPostSystemReadyMessages = new ArrayList<>();
14055            }
14056            mPostSystemReadyMessages.add(msg);
14057        }
14058    }
14059
14060    void startCleaningPackages() {
14061        // reader
14062        if (!isExternalMediaAvailable()) {
14063            return;
14064        }
14065        synchronized (mPackages) {
14066            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
14067                return;
14068            }
14069        }
14070        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
14071        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
14072        IActivityManager am = ActivityManager.getService();
14073        if (am != null) {
14074            int dcsUid = -1;
14075            synchronized (mPackages) {
14076                if (!mDefaultContainerWhitelisted) {
14077                    mDefaultContainerWhitelisted = true;
14078                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
14079                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
14080                }
14081            }
14082            try {
14083                if (dcsUid > 0) {
14084                    am.backgroundWhitelistUid(dcsUid);
14085                }
14086                am.startService(null, intent, null, false, mContext.getOpPackageName(),
14087                        UserHandle.USER_SYSTEM);
14088            } catch (RemoteException e) {
14089            }
14090        }
14091    }
14092
14093    @Override
14094    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
14095            int installFlags, String installerPackageName, int userId) {
14096        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
14097
14098        final int callingUid = Binder.getCallingUid();
14099        enforceCrossUserPermission(callingUid, userId,
14100                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
14101
14102        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14103            try {
14104                if (observer != null) {
14105                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
14106                }
14107            } catch (RemoteException re) {
14108            }
14109            return;
14110        }
14111
14112        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
14113            installFlags |= PackageManager.INSTALL_FROM_ADB;
14114
14115        } else {
14116            // Caller holds INSTALL_PACKAGES permission, so we're less strict
14117            // about installerPackageName.
14118
14119            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
14120            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
14121        }
14122
14123        UserHandle user;
14124        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
14125            user = UserHandle.ALL;
14126        } else {
14127            user = new UserHandle(userId);
14128        }
14129
14130        // Only system components can circumvent runtime permissions when installing.
14131        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
14132                && mContext.checkCallingOrSelfPermission(Manifest.permission
14133                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
14134            throw new SecurityException("You need the "
14135                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
14136                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
14137        }
14138
14139        if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
14140                || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
14141            throw new IllegalArgumentException(
14142                    "New installs into ASEC containers no longer supported");
14143        }
14144
14145        final File originFile = new File(originPath);
14146        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
14147
14148        final Message msg = mHandler.obtainMessage(INIT_COPY);
14149        final VerificationInfo verificationInfo = new VerificationInfo(
14150                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
14151        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
14152                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
14153                null /*packageAbiOverride*/, null /*grantedPermissions*/,
14154                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
14155        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
14156        msg.obj = params;
14157
14158        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
14159                System.identityHashCode(msg.obj));
14160        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14161                System.identityHashCode(msg.obj));
14162
14163        mHandler.sendMessage(msg);
14164    }
14165
14166
14167    /**
14168     * Ensure that the install reason matches what we know about the package installer (e.g. whether
14169     * it is acting on behalf on an enterprise or the user).
14170     *
14171     * Note that the ordering of the conditionals in this method is important. The checks we perform
14172     * are as follows, in this order:
14173     *
14174     * 1) If the install is being performed by a system app, we can trust the app to have set the
14175     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
14176     *    what it is.
14177     * 2) If the install is being performed by a device or profile owner app, the install reason
14178     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
14179     *    set the install reason correctly. If the app targets an older SDK version where install
14180     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
14181     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
14182     * 3) In all other cases, the install is being performed by a regular app that is neither part
14183     *    of the system nor a device or profile owner. We have no reason to believe that this app is
14184     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
14185     *    set to enterprise policy and if so, change it to unknown instead.
14186     */
14187    private int fixUpInstallReason(String installerPackageName, int installerUid,
14188            int installReason) {
14189        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
14190                == PERMISSION_GRANTED) {
14191            // If the install is being performed by a system app, we trust that app to have set the
14192            // install reason correctly.
14193            return installReason;
14194        }
14195
14196        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
14197            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
14198        if (dpm != null) {
14199            ComponentName owner = null;
14200            try {
14201                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
14202                if (owner == null) {
14203                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
14204                }
14205            } catch (RemoteException e) {
14206            }
14207            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
14208                // If the install is being performed by a device or profile owner, the install
14209                // reason should be enterprise policy.
14210                return PackageManager.INSTALL_REASON_POLICY;
14211            }
14212        }
14213
14214        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
14215            // If the install is being performed by a regular app (i.e. neither system app nor
14216            // device or profile owner), we have no reason to believe that the app is acting on
14217            // behalf of an enterprise. If the app set the install reason to enterprise policy,
14218            // change it to unknown instead.
14219            return PackageManager.INSTALL_REASON_UNKNOWN;
14220        }
14221
14222        // If the install is being performed by a regular app and the install reason was set to any
14223        // value but enterprise policy, leave the install reason unchanged.
14224        return installReason;
14225    }
14226
14227    void installStage(String packageName, File stagedDir, String stagedCid,
14228            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
14229            String installerPackageName, int installerUid, UserHandle user,
14230            Certificate[][] certificates) {
14231        if (DEBUG_EPHEMERAL) {
14232            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14233                Slog.d(TAG, "Ephemeral install of " + packageName);
14234            }
14235        }
14236        final VerificationInfo verificationInfo = new VerificationInfo(
14237                sessionParams.originatingUri, sessionParams.referrerUri,
14238                sessionParams.originatingUid, installerUid);
14239
14240        final OriginInfo origin;
14241        if (stagedDir != null) {
14242            origin = OriginInfo.fromStagedFile(stagedDir);
14243        } else {
14244            origin = OriginInfo.fromStagedContainer(stagedCid);
14245        }
14246
14247        final Message msg = mHandler.obtainMessage(INIT_COPY);
14248        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
14249                sessionParams.installReason);
14250        final InstallParams params = new InstallParams(origin, null, observer,
14251                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
14252                verificationInfo, user, sessionParams.abiOverride,
14253                sessionParams.grantedRuntimePermissions, certificates, installReason);
14254        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
14255        msg.obj = params;
14256
14257        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
14258                System.identityHashCode(msg.obj));
14259        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14260                System.identityHashCode(msg.obj));
14261
14262        mHandler.sendMessage(msg);
14263    }
14264
14265    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
14266            int userId) {
14267        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
14268        sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId);
14269
14270        // Send a session commit broadcast
14271        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
14272        info.installReason = pkgSetting.getInstallReason(userId);
14273        info.appPackageName = packageName;
14274        sendSessionCommitBroadcast(info, userId);
14275    }
14276
14277    public void sendPackageAddedForNewUsers(String packageName, boolean isSystem, int appId, int... userIds) {
14278        if (ArrayUtils.isEmpty(userIds)) {
14279            return;
14280        }
14281        Bundle extras = new Bundle(1);
14282        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
14283        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
14284
14285        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
14286                packageName, extras, 0, null, null, userIds);
14287        if (isSystem) {
14288            mHandler.post(() -> {
14289                        for (int userId : userIds) {
14290                            sendBootCompletedBroadcastToSystemApp(packageName, userId);
14291                        }
14292                    }
14293            );
14294        }
14295    }
14296
14297    /**
14298     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
14299     * automatically without needing an explicit launch.
14300     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
14301     */
14302    private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) {
14303        // If user is not running, the app didn't miss any broadcast
14304        if (!mUserManagerInternal.isUserRunning(userId)) {
14305            return;
14306        }
14307        final IActivityManager am = ActivityManager.getService();
14308        try {
14309            // Deliver LOCKED_BOOT_COMPLETED first
14310            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
14311                    .setPackage(packageName);
14312            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
14313            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
14314                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14315
14316            // Deliver BOOT_COMPLETED only if user is unlocked
14317            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
14318                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
14319                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
14320                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14321            }
14322        } catch (RemoteException e) {
14323            throw e.rethrowFromSystemServer();
14324        }
14325    }
14326
14327    @Override
14328    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
14329            int userId) {
14330        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14331        PackageSetting pkgSetting;
14332        final int callingUid = Binder.getCallingUid();
14333        enforceCrossUserPermission(callingUid, userId,
14334                true /* requireFullPermission */, true /* checkShell */,
14335                "setApplicationHiddenSetting for user " + userId);
14336
14337        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
14338            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
14339            return false;
14340        }
14341
14342        long callingId = Binder.clearCallingIdentity();
14343        try {
14344            boolean sendAdded = false;
14345            boolean sendRemoved = false;
14346            // writer
14347            synchronized (mPackages) {
14348                pkgSetting = mSettings.mPackages.get(packageName);
14349                if (pkgSetting == null) {
14350                    return false;
14351                }
14352                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14353                    return false;
14354                }
14355                // Do not allow "android" is being disabled
14356                if ("android".equals(packageName)) {
14357                    Slog.w(TAG, "Cannot hide package: android");
14358                    return false;
14359                }
14360                // Cannot hide static shared libs as they are considered
14361                // a part of the using app (emulating static linking). Also
14362                // static libs are installed always on internal storage.
14363                PackageParser.Package pkg = mPackages.get(packageName);
14364                if (pkg != null && pkg.staticSharedLibName != null) {
14365                    Slog.w(TAG, "Cannot hide package: " + packageName
14366                            + " providing static shared library: "
14367                            + pkg.staticSharedLibName);
14368                    return false;
14369                }
14370                // Only allow protected packages to hide themselves.
14371                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
14372                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14373                    Slog.w(TAG, "Not hiding protected package: " + packageName);
14374                    return false;
14375                }
14376
14377                if (pkgSetting.getHidden(userId) != hidden) {
14378                    pkgSetting.setHidden(hidden, userId);
14379                    mSettings.writePackageRestrictionsLPr(userId);
14380                    if (hidden) {
14381                        sendRemoved = true;
14382                    } else {
14383                        sendAdded = true;
14384                    }
14385                }
14386            }
14387            if (sendAdded) {
14388                sendPackageAddedForUser(packageName, pkgSetting, userId);
14389                return true;
14390            }
14391            if (sendRemoved) {
14392                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
14393                        "hiding pkg");
14394                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
14395                return true;
14396            }
14397        } finally {
14398            Binder.restoreCallingIdentity(callingId);
14399        }
14400        return false;
14401    }
14402
14403    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
14404            int userId) {
14405        final PackageRemovedInfo info = new PackageRemovedInfo(this);
14406        info.removedPackage = packageName;
14407        info.installerPackageName = pkgSetting.installerPackageName;
14408        info.removedUsers = new int[] {userId};
14409        info.broadcastUsers = new int[] {userId};
14410        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
14411        info.sendPackageRemovedBroadcasts(true /*killApp*/);
14412    }
14413
14414    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
14415        if (pkgList.length > 0) {
14416            Bundle extras = new Bundle(1);
14417            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
14418
14419            sendPackageBroadcast(
14420                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
14421                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
14422                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
14423                    new int[] {userId});
14424        }
14425    }
14426
14427    /**
14428     * Returns true if application is not found or there was an error. Otherwise it returns
14429     * the hidden state of the package for the given user.
14430     */
14431    @Override
14432    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
14433        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14434        final int callingUid = Binder.getCallingUid();
14435        enforceCrossUserPermission(callingUid, userId,
14436                true /* requireFullPermission */, false /* checkShell */,
14437                "getApplicationHidden for user " + userId);
14438        PackageSetting ps;
14439        long callingId = Binder.clearCallingIdentity();
14440        try {
14441            // writer
14442            synchronized (mPackages) {
14443                ps = mSettings.mPackages.get(packageName);
14444                if (ps == null) {
14445                    return true;
14446                }
14447                if (filterAppAccessLPr(ps, callingUid, userId)) {
14448                    return true;
14449                }
14450                return ps.getHidden(userId);
14451            }
14452        } finally {
14453            Binder.restoreCallingIdentity(callingId);
14454        }
14455    }
14456
14457    /**
14458     * @hide
14459     */
14460    @Override
14461    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
14462            int installReason) {
14463        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
14464                null);
14465        PackageSetting pkgSetting;
14466        final int callingUid = Binder.getCallingUid();
14467        enforceCrossUserPermission(callingUid, userId,
14468                true /* requireFullPermission */, true /* checkShell */,
14469                "installExistingPackage for user " + userId);
14470        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14471            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
14472        }
14473
14474        long callingId = Binder.clearCallingIdentity();
14475        try {
14476            boolean installed = false;
14477            final boolean instantApp =
14478                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14479            final boolean fullApp =
14480                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
14481
14482            // writer
14483            synchronized (mPackages) {
14484                pkgSetting = mSettings.mPackages.get(packageName);
14485                if (pkgSetting == null) {
14486                    return PackageManager.INSTALL_FAILED_INVALID_URI;
14487                }
14488                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
14489                    // only allow the existing package to be used if it's installed as a full
14490                    // application for at least one user
14491                    boolean installAllowed = false;
14492                    for (int checkUserId : sUserManager.getUserIds()) {
14493                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
14494                        if (installAllowed) {
14495                            break;
14496                        }
14497                    }
14498                    if (!installAllowed) {
14499                        return PackageManager.INSTALL_FAILED_INVALID_URI;
14500                    }
14501                }
14502                if (!pkgSetting.getInstalled(userId)) {
14503                    pkgSetting.setInstalled(true, userId);
14504                    pkgSetting.setHidden(false, userId);
14505                    pkgSetting.setInstallReason(installReason, userId);
14506                    mSettings.writePackageRestrictionsLPr(userId);
14507                    mSettings.writeKernelMappingLPr(pkgSetting);
14508                    installed = true;
14509                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14510                    // upgrade app from instant to full; we don't allow app downgrade
14511                    installed = true;
14512                }
14513                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
14514            }
14515
14516            if (installed) {
14517                if (pkgSetting.pkg != null) {
14518                    synchronized (mInstallLock) {
14519                        // We don't need to freeze for a brand new install
14520                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
14521                    }
14522                }
14523                sendPackageAddedForUser(packageName, pkgSetting, userId);
14524                synchronized (mPackages) {
14525                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
14526                }
14527            }
14528        } finally {
14529            Binder.restoreCallingIdentity(callingId);
14530        }
14531
14532        return PackageManager.INSTALL_SUCCEEDED;
14533    }
14534
14535    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
14536            boolean instantApp, boolean fullApp) {
14537        // no state specified; do nothing
14538        if (!instantApp && !fullApp) {
14539            return;
14540        }
14541        if (userId != UserHandle.USER_ALL) {
14542            if (instantApp && !pkgSetting.getInstantApp(userId)) {
14543                pkgSetting.setInstantApp(true /*instantApp*/, userId);
14544            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14545                pkgSetting.setInstantApp(false /*instantApp*/, userId);
14546            }
14547        } else {
14548            for (int currentUserId : sUserManager.getUserIds()) {
14549                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
14550                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
14551                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
14552                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
14553                }
14554            }
14555        }
14556    }
14557
14558    boolean isUserRestricted(int userId, String restrictionKey) {
14559        Bundle restrictions = sUserManager.getUserRestrictions(userId);
14560        if (restrictions.getBoolean(restrictionKey, false)) {
14561            Log.w(TAG, "User is restricted: " + restrictionKey);
14562            return true;
14563        }
14564        return false;
14565    }
14566
14567    @Override
14568    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
14569            int userId) {
14570        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14571        final int callingUid = Binder.getCallingUid();
14572        enforceCrossUserPermission(callingUid, userId,
14573                true /* requireFullPermission */, true /* checkShell */,
14574                "setPackagesSuspended for user " + userId);
14575
14576        if (ArrayUtils.isEmpty(packageNames)) {
14577            return packageNames;
14578        }
14579
14580        // List of package names for whom the suspended state has changed.
14581        List<String> changedPackages = new ArrayList<>(packageNames.length);
14582        // List of package names for whom the suspended state is not set as requested in this
14583        // method.
14584        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
14585        long callingId = Binder.clearCallingIdentity();
14586        try {
14587            for (int i = 0; i < packageNames.length; i++) {
14588                String packageName = packageNames[i];
14589                boolean changed = false;
14590                final int appId;
14591                synchronized (mPackages) {
14592                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
14593                    if (pkgSetting == null
14594                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14595                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
14596                                + "\". Skipping suspending/un-suspending.");
14597                        unactionedPackages.add(packageName);
14598                        continue;
14599                    }
14600                    appId = pkgSetting.appId;
14601                    if (pkgSetting.getSuspended(userId) != suspended) {
14602                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
14603                            unactionedPackages.add(packageName);
14604                            continue;
14605                        }
14606                        pkgSetting.setSuspended(suspended, userId);
14607                        mSettings.writePackageRestrictionsLPr(userId);
14608                        changed = true;
14609                        changedPackages.add(packageName);
14610                    }
14611                }
14612
14613                if (changed && suspended) {
14614                    killApplication(packageName, UserHandle.getUid(userId, appId),
14615                            "suspending package");
14616                }
14617            }
14618        } finally {
14619            Binder.restoreCallingIdentity(callingId);
14620        }
14621
14622        if (!changedPackages.isEmpty()) {
14623            sendPackagesSuspendedForUser(changedPackages.toArray(
14624                    new String[changedPackages.size()]), userId, suspended);
14625        }
14626
14627        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
14628    }
14629
14630    @Override
14631    public boolean isPackageSuspendedForUser(String packageName, int userId) {
14632        final int callingUid = Binder.getCallingUid();
14633        enforceCrossUserPermission(callingUid, userId,
14634                true /* requireFullPermission */, false /* checkShell */,
14635                "isPackageSuspendedForUser for user " + userId);
14636        synchronized (mPackages) {
14637            final PackageSetting ps = mSettings.mPackages.get(packageName);
14638            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
14639                throw new IllegalArgumentException("Unknown target package: " + packageName);
14640            }
14641            return ps.getSuspended(userId);
14642        }
14643    }
14644
14645    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
14646        if (isPackageDeviceAdmin(packageName, userId)) {
14647            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14648                    + "\": has an active device admin");
14649            return false;
14650        }
14651
14652        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
14653        if (packageName.equals(activeLauncherPackageName)) {
14654            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14655                    + "\": contains the active launcher");
14656            return false;
14657        }
14658
14659        if (packageName.equals(mRequiredInstallerPackage)) {
14660            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14661                    + "\": required for package installation");
14662            return false;
14663        }
14664
14665        if (packageName.equals(mRequiredUninstallerPackage)) {
14666            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14667                    + "\": required for package uninstallation");
14668            return false;
14669        }
14670
14671        if (packageName.equals(mRequiredVerifierPackage)) {
14672            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14673                    + "\": required for package verification");
14674            return false;
14675        }
14676
14677        if (packageName.equals(getDefaultDialerPackageName(userId))) {
14678            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14679                    + "\": is the default dialer");
14680            return false;
14681        }
14682
14683        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14684            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14685                    + "\": protected package");
14686            return false;
14687        }
14688
14689        // Cannot suspend static shared libs as they are considered
14690        // a part of the using app (emulating static linking). Also
14691        // static libs are installed always on internal storage.
14692        PackageParser.Package pkg = mPackages.get(packageName);
14693        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
14694            Slog.w(TAG, "Cannot suspend package: " + packageName
14695                    + " providing static shared library: "
14696                    + pkg.staticSharedLibName);
14697            return false;
14698        }
14699
14700        return true;
14701    }
14702
14703    private String getActiveLauncherPackageName(int userId) {
14704        Intent intent = new Intent(Intent.ACTION_MAIN);
14705        intent.addCategory(Intent.CATEGORY_HOME);
14706        ResolveInfo resolveInfo = resolveIntent(
14707                intent,
14708                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
14709                PackageManager.MATCH_DEFAULT_ONLY,
14710                userId);
14711
14712        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
14713    }
14714
14715    private String getDefaultDialerPackageName(int userId) {
14716        synchronized (mPackages) {
14717            return mSettings.getDefaultDialerPackageNameLPw(userId);
14718        }
14719    }
14720
14721    @Override
14722    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
14723        mContext.enforceCallingOrSelfPermission(
14724                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14725                "Only package verification agents can verify applications");
14726
14727        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14728        final PackageVerificationResponse response = new PackageVerificationResponse(
14729                verificationCode, Binder.getCallingUid());
14730        msg.arg1 = id;
14731        msg.obj = response;
14732        mHandler.sendMessage(msg);
14733    }
14734
14735    @Override
14736    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
14737            long millisecondsToDelay) {
14738        mContext.enforceCallingOrSelfPermission(
14739                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14740                "Only package verification agents can extend verification timeouts");
14741
14742        final PackageVerificationState state = mPendingVerification.get(id);
14743        final PackageVerificationResponse response = new PackageVerificationResponse(
14744                verificationCodeAtTimeout, Binder.getCallingUid());
14745
14746        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
14747            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
14748        }
14749        if (millisecondsToDelay < 0) {
14750            millisecondsToDelay = 0;
14751        }
14752        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
14753                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
14754            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
14755        }
14756
14757        if ((state != null) && !state.timeoutExtended()) {
14758            state.extendTimeout();
14759
14760            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14761            msg.arg1 = id;
14762            msg.obj = response;
14763            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
14764        }
14765    }
14766
14767    private void broadcastPackageVerified(int verificationId, Uri packageUri,
14768            int verificationCode, UserHandle user) {
14769        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
14770        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
14771        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14772        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14773        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
14774
14775        mContext.sendBroadcastAsUser(intent, user,
14776                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
14777    }
14778
14779    private ComponentName matchComponentForVerifier(String packageName,
14780            List<ResolveInfo> receivers) {
14781        ActivityInfo targetReceiver = null;
14782
14783        final int NR = receivers.size();
14784        for (int i = 0; i < NR; i++) {
14785            final ResolveInfo info = receivers.get(i);
14786            if (info.activityInfo == null) {
14787                continue;
14788            }
14789
14790            if (packageName.equals(info.activityInfo.packageName)) {
14791                targetReceiver = info.activityInfo;
14792                break;
14793            }
14794        }
14795
14796        if (targetReceiver == null) {
14797            return null;
14798        }
14799
14800        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
14801    }
14802
14803    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
14804            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
14805        if (pkgInfo.verifiers.length == 0) {
14806            return null;
14807        }
14808
14809        final int N = pkgInfo.verifiers.length;
14810        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
14811        for (int i = 0; i < N; i++) {
14812            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
14813
14814            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
14815                    receivers);
14816            if (comp == null) {
14817                continue;
14818            }
14819
14820            final int verifierUid = getUidForVerifier(verifierInfo);
14821            if (verifierUid == -1) {
14822                continue;
14823            }
14824
14825            if (DEBUG_VERIFY) {
14826                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
14827                        + " with the correct signature");
14828            }
14829            sufficientVerifiers.add(comp);
14830            verificationState.addSufficientVerifier(verifierUid);
14831        }
14832
14833        return sufficientVerifiers;
14834    }
14835
14836    private int getUidForVerifier(VerifierInfo verifierInfo) {
14837        synchronized (mPackages) {
14838            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
14839            if (pkg == null) {
14840                return -1;
14841            } else if (pkg.mSignatures.length != 1) {
14842                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14843                        + " has more than one signature; ignoring");
14844                return -1;
14845            }
14846
14847            /*
14848             * If the public key of the package's signature does not match
14849             * our expected public key, then this is a different package and
14850             * we should skip.
14851             */
14852
14853            final byte[] expectedPublicKey;
14854            try {
14855                final Signature verifierSig = pkg.mSignatures[0];
14856                final PublicKey publicKey = verifierSig.getPublicKey();
14857                expectedPublicKey = publicKey.getEncoded();
14858            } catch (CertificateException e) {
14859                return -1;
14860            }
14861
14862            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
14863
14864            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
14865                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14866                        + " does not have the expected public key; ignoring");
14867                return -1;
14868            }
14869
14870            return pkg.applicationInfo.uid;
14871        }
14872    }
14873
14874    @Override
14875    public void finishPackageInstall(int token, boolean didLaunch) {
14876        enforceSystemOrRoot("Only the system is allowed to finish installs");
14877
14878        if (DEBUG_INSTALL) {
14879            Slog.v(TAG, "BM finishing package install for " + token);
14880        }
14881        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14882
14883        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
14884        mHandler.sendMessage(msg);
14885    }
14886
14887    /**
14888     * Get the verification agent timeout.  Used for both the APK verifier and the
14889     * intent filter verifier.
14890     *
14891     * @return verification timeout in milliseconds
14892     */
14893    private long getVerificationTimeout() {
14894        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
14895                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
14896                DEFAULT_VERIFICATION_TIMEOUT);
14897    }
14898
14899    /**
14900     * Get the default verification agent response code.
14901     *
14902     * @return default verification response code
14903     */
14904    private int getDefaultVerificationResponse(UserHandle user) {
14905        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
14906            return PackageManager.VERIFICATION_REJECT;
14907        }
14908        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14909                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
14910                DEFAULT_VERIFICATION_RESPONSE);
14911    }
14912
14913    /**
14914     * Check whether or not package verification has been enabled.
14915     *
14916     * @return true if verification should be performed
14917     */
14918    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
14919        if (!DEFAULT_VERIFY_ENABLE) {
14920            return false;
14921        }
14922
14923        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
14924
14925        // Check if installing from ADB
14926        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
14927            // Do not run verification in a test harness environment
14928            if (ActivityManager.isRunningInTestHarness()) {
14929                return false;
14930            }
14931            if (ensureVerifyAppsEnabled) {
14932                return true;
14933            }
14934            // Check if the developer does not want package verification for ADB installs
14935            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14936                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
14937                return false;
14938            }
14939        } else {
14940            // only when not installed from ADB, skip verification for instant apps when
14941            // the installer and verifier are the same.
14942            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14943                if (mInstantAppInstallerActivity != null
14944                        && mInstantAppInstallerActivity.packageName.equals(
14945                                mRequiredVerifierPackage)) {
14946                    try {
14947                        mContext.getSystemService(AppOpsManager.class)
14948                                .checkPackage(installerUid, mRequiredVerifierPackage);
14949                        if (DEBUG_VERIFY) {
14950                            Slog.i(TAG, "disable verification for instant app");
14951                        }
14952                        return false;
14953                    } catch (SecurityException ignore) { }
14954                }
14955            }
14956        }
14957
14958        if (ensureVerifyAppsEnabled) {
14959            return true;
14960        }
14961
14962        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14963                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
14964    }
14965
14966    @Override
14967    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
14968            throws RemoteException {
14969        mContext.enforceCallingOrSelfPermission(
14970                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
14971                "Only intentfilter verification agents can verify applications");
14972
14973        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
14974        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
14975                Binder.getCallingUid(), verificationCode, failedDomains);
14976        msg.arg1 = id;
14977        msg.obj = response;
14978        mHandler.sendMessage(msg);
14979    }
14980
14981    @Override
14982    public int getIntentVerificationStatus(String packageName, int userId) {
14983        final int callingUid = Binder.getCallingUid();
14984        if (getInstantAppPackageName(callingUid) != null) {
14985            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14986        }
14987        synchronized (mPackages) {
14988            final PackageSetting ps = mSettings.mPackages.get(packageName);
14989            if (ps == null
14990                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14991                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14992            }
14993            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
14994        }
14995    }
14996
14997    @Override
14998    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
14999        mContext.enforceCallingOrSelfPermission(
15000                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15001
15002        boolean result = false;
15003        synchronized (mPackages) {
15004            final PackageSetting ps = mSettings.mPackages.get(packageName);
15005            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15006                return false;
15007            }
15008            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
15009        }
15010        if (result) {
15011            scheduleWritePackageRestrictionsLocked(userId);
15012        }
15013        return result;
15014    }
15015
15016    @Override
15017    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
15018            String packageName) {
15019        final int callingUid = Binder.getCallingUid();
15020        if (getInstantAppPackageName(callingUid) != null) {
15021            return ParceledListSlice.emptyList();
15022        }
15023        synchronized (mPackages) {
15024            final PackageSetting ps = mSettings.mPackages.get(packageName);
15025            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15026                return ParceledListSlice.emptyList();
15027            }
15028            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
15029        }
15030    }
15031
15032    @Override
15033    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
15034        if (TextUtils.isEmpty(packageName)) {
15035            return ParceledListSlice.emptyList();
15036        }
15037        final int callingUid = Binder.getCallingUid();
15038        final int callingUserId = UserHandle.getUserId(callingUid);
15039        synchronized (mPackages) {
15040            PackageParser.Package pkg = mPackages.get(packageName);
15041            if (pkg == null || pkg.activities == null) {
15042                return ParceledListSlice.emptyList();
15043            }
15044            if (pkg.mExtras == null) {
15045                return ParceledListSlice.emptyList();
15046            }
15047            final PackageSetting ps = (PackageSetting) pkg.mExtras;
15048            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
15049                return ParceledListSlice.emptyList();
15050            }
15051            final int count = pkg.activities.size();
15052            ArrayList<IntentFilter> result = new ArrayList<>();
15053            for (int n=0; n<count; n++) {
15054                PackageParser.Activity activity = pkg.activities.get(n);
15055                if (activity.intents != null && activity.intents.size() > 0) {
15056                    result.addAll(activity.intents);
15057                }
15058            }
15059            return new ParceledListSlice<>(result);
15060        }
15061    }
15062
15063    @Override
15064    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
15065        mContext.enforceCallingOrSelfPermission(
15066                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15067
15068        synchronized (mPackages) {
15069            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
15070            if (packageName != null) {
15071                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
15072                        packageName, userId);
15073            }
15074            return result;
15075        }
15076    }
15077
15078    @Override
15079    public String getDefaultBrowserPackageName(int userId) {
15080        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15081            return null;
15082        }
15083        synchronized (mPackages) {
15084            return mSettings.getDefaultBrowserPackageNameLPw(userId);
15085        }
15086    }
15087
15088    /**
15089     * Get the "allow unknown sources" setting.
15090     *
15091     * @return the current "allow unknown sources" setting
15092     */
15093    private int getUnknownSourcesSettings() {
15094        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
15095                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
15096                -1);
15097    }
15098
15099    @Override
15100    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
15101        final int callingUid = Binder.getCallingUid();
15102        if (getInstantAppPackageName(callingUid) != null) {
15103            return;
15104        }
15105        // writer
15106        synchronized (mPackages) {
15107            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
15108            if (targetPackageSetting == null
15109                    || filterAppAccessLPr(
15110                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
15111                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
15112            }
15113
15114            PackageSetting installerPackageSetting;
15115            if (installerPackageName != null) {
15116                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
15117                if (installerPackageSetting == null) {
15118                    throw new IllegalArgumentException("Unknown installer package: "
15119                            + installerPackageName);
15120                }
15121            } else {
15122                installerPackageSetting = null;
15123            }
15124
15125            Signature[] callerSignature;
15126            Object obj = mSettings.getUserIdLPr(callingUid);
15127            if (obj != null) {
15128                if (obj instanceof SharedUserSetting) {
15129                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
15130                } else if (obj instanceof PackageSetting) {
15131                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
15132                } else {
15133                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
15134                }
15135            } else {
15136                throw new SecurityException("Unknown calling UID: " + callingUid);
15137            }
15138
15139            // Verify: can't set installerPackageName to a package that is
15140            // not signed with the same cert as the caller.
15141            if (installerPackageSetting != null) {
15142                if (compareSignatures(callerSignature,
15143                        installerPackageSetting.signatures.mSignatures)
15144                        != PackageManager.SIGNATURE_MATCH) {
15145                    throw new SecurityException(
15146                            "Caller does not have same cert as new installer package "
15147                            + installerPackageName);
15148                }
15149            }
15150
15151            // Verify: if target already has an installer package, it must
15152            // be signed with the same cert as the caller.
15153            if (targetPackageSetting.installerPackageName != null) {
15154                PackageSetting setting = mSettings.mPackages.get(
15155                        targetPackageSetting.installerPackageName);
15156                // If the currently set package isn't valid, then it's always
15157                // okay to change it.
15158                if (setting != null) {
15159                    if (compareSignatures(callerSignature,
15160                            setting.signatures.mSignatures)
15161                            != PackageManager.SIGNATURE_MATCH) {
15162                        throw new SecurityException(
15163                                "Caller does not have same cert as old installer package "
15164                                + targetPackageSetting.installerPackageName);
15165                    }
15166                }
15167            }
15168
15169            // Okay!
15170            targetPackageSetting.installerPackageName = installerPackageName;
15171            if (installerPackageName != null) {
15172                mSettings.mInstallerPackages.add(installerPackageName);
15173            }
15174            scheduleWriteSettingsLocked();
15175        }
15176    }
15177
15178    @Override
15179    public void setApplicationCategoryHint(String packageName, int categoryHint,
15180            String callerPackageName) {
15181        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15182            throw new SecurityException("Instant applications don't have access to this method");
15183        }
15184        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
15185                callerPackageName);
15186        synchronized (mPackages) {
15187            PackageSetting ps = mSettings.mPackages.get(packageName);
15188            if (ps == null) {
15189                throw new IllegalArgumentException("Unknown target package " + packageName);
15190            }
15191            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15192                throw new IllegalArgumentException("Unknown target package " + packageName);
15193            }
15194            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
15195                throw new IllegalArgumentException("Calling package " + callerPackageName
15196                        + " is not installer for " + packageName);
15197            }
15198
15199            if (ps.categoryHint != categoryHint) {
15200                ps.categoryHint = categoryHint;
15201                scheduleWriteSettingsLocked();
15202            }
15203        }
15204    }
15205
15206    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
15207        // Queue up an async operation since the package installation may take a little while.
15208        mHandler.post(new Runnable() {
15209            public void run() {
15210                mHandler.removeCallbacks(this);
15211                 // Result object to be returned
15212                PackageInstalledInfo res = new PackageInstalledInfo();
15213                res.setReturnCode(currentStatus);
15214                res.uid = -1;
15215                res.pkg = null;
15216                res.removedInfo = null;
15217                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15218                    args.doPreInstall(res.returnCode);
15219                    synchronized (mInstallLock) {
15220                        installPackageTracedLI(args, res);
15221                    }
15222                    args.doPostInstall(res.returnCode, res.uid);
15223                }
15224
15225                // A restore should be performed at this point if (a) the install
15226                // succeeded, (b) the operation is not an update, and (c) the new
15227                // package has not opted out of backup participation.
15228                final boolean update = res.removedInfo != null
15229                        && res.removedInfo.removedPackage != null;
15230                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
15231                boolean doRestore = !update
15232                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
15233
15234                // Set up the post-install work request bookkeeping.  This will be used
15235                // and cleaned up by the post-install event handling regardless of whether
15236                // there's a restore pass performed.  Token values are >= 1.
15237                int token;
15238                if (mNextInstallToken < 0) mNextInstallToken = 1;
15239                token = mNextInstallToken++;
15240
15241                PostInstallData data = new PostInstallData(args, res);
15242                mRunningInstalls.put(token, data);
15243                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
15244
15245                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
15246                    // Pass responsibility to the Backup Manager.  It will perform a
15247                    // restore if appropriate, then pass responsibility back to the
15248                    // Package Manager to run the post-install observer callbacks
15249                    // and broadcasts.
15250                    IBackupManager bm = IBackupManager.Stub.asInterface(
15251                            ServiceManager.getService(Context.BACKUP_SERVICE));
15252                    if (bm != null) {
15253                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
15254                                + " to BM for possible restore");
15255                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
15256                        try {
15257                            // TODO: http://b/22388012
15258                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
15259                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
15260                            } else {
15261                                doRestore = false;
15262                            }
15263                        } catch (RemoteException e) {
15264                            // can't happen; the backup manager is local
15265                        } catch (Exception e) {
15266                            Slog.e(TAG, "Exception trying to enqueue restore", e);
15267                            doRestore = false;
15268                        }
15269                    } else {
15270                        Slog.e(TAG, "Backup Manager not found!");
15271                        doRestore = false;
15272                    }
15273                }
15274
15275                if (!doRestore) {
15276                    // No restore possible, or the Backup Manager was mysteriously not
15277                    // available -- just fire the post-install work request directly.
15278                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
15279
15280                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
15281
15282                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
15283                    mHandler.sendMessage(msg);
15284                }
15285            }
15286        });
15287    }
15288
15289    /**
15290     * Callback from PackageSettings whenever an app is first transitioned out of the
15291     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
15292     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
15293     * here whether the app is the target of an ongoing install, and only send the
15294     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
15295     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
15296     * handling.
15297     */
15298    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
15299        // Serialize this with the rest of the install-process message chain.  In the
15300        // restore-at-install case, this Runnable will necessarily run before the
15301        // POST_INSTALL message is processed, so the contents of mRunningInstalls
15302        // are coherent.  In the non-restore case, the app has already completed install
15303        // and been launched through some other means, so it is not in a problematic
15304        // state for observers to see the FIRST_LAUNCH signal.
15305        mHandler.post(new Runnable() {
15306            @Override
15307            public void run() {
15308                for (int i = 0; i < mRunningInstalls.size(); i++) {
15309                    final PostInstallData data = mRunningInstalls.valueAt(i);
15310                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15311                        continue;
15312                    }
15313                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
15314                        // right package; but is it for the right user?
15315                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
15316                            if (userId == data.res.newUsers[uIndex]) {
15317                                if (DEBUG_BACKUP) {
15318                                    Slog.i(TAG, "Package " + pkgName
15319                                            + " being restored so deferring FIRST_LAUNCH");
15320                                }
15321                                return;
15322                            }
15323                        }
15324                    }
15325                }
15326                // didn't find it, so not being restored
15327                if (DEBUG_BACKUP) {
15328                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
15329                }
15330                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
15331            }
15332        });
15333    }
15334
15335    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
15336        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
15337                installerPkg, null, userIds);
15338    }
15339
15340    private abstract class HandlerParams {
15341        private static final int MAX_RETRIES = 4;
15342
15343        /**
15344         * Number of times startCopy() has been attempted and had a non-fatal
15345         * error.
15346         */
15347        private int mRetries = 0;
15348
15349        /** User handle for the user requesting the information or installation. */
15350        private final UserHandle mUser;
15351        String traceMethod;
15352        int traceCookie;
15353
15354        HandlerParams(UserHandle user) {
15355            mUser = user;
15356        }
15357
15358        UserHandle getUser() {
15359            return mUser;
15360        }
15361
15362        HandlerParams setTraceMethod(String traceMethod) {
15363            this.traceMethod = traceMethod;
15364            return this;
15365        }
15366
15367        HandlerParams setTraceCookie(int traceCookie) {
15368            this.traceCookie = traceCookie;
15369            return this;
15370        }
15371
15372        final boolean startCopy() {
15373            boolean res;
15374            try {
15375                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
15376
15377                if (++mRetries > MAX_RETRIES) {
15378                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
15379                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
15380                    handleServiceError();
15381                    return false;
15382                } else {
15383                    handleStartCopy();
15384                    res = true;
15385                }
15386            } catch (RemoteException e) {
15387                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
15388                mHandler.sendEmptyMessage(MCS_RECONNECT);
15389                res = false;
15390            }
15391            handleReturnCode();
15392            return res;
15393        }
15394
15395        final void serviceError() {
15396            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
15397            handleServiceError();
15398            handleReturnCode();
15399        }
15400
15401        abstract void handleStartCopy() throws RemoteException;
15402        abstract void handleServiceError();
15403        abstract void handleReturnCode();
15404    }
15405
15406    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
15407        for (File path : paths) {
15408            try {
15409                mcs.clearDirectory(path.getAbsolutePath());
15410            } catch (RemoteException e) {
15411            }
15412        }
15413    }
15414
15415    static class OriginInfo {
15416        /**
15417         * Location where install is coming from, before it has been
15418         * copied/renamed into place. This could be a single monolithic APK
15419         * file, or a cluster directory. This location may be untrusted.
15420         */
15421        final File file;
15422        final String cid;
15423
15424        /**
15425         * Flag indicating that {@link #file} or {@link #cid} has already been
15426         * staged, meaning downstream users don't need to defensively copy the
15427         * contents.
15428         */
15429        final boolean staged;
15430
15431        /**
15432         * Flag indicating that {@link #file} or {@link #cid} is an already
15433         * installed app that is being moved.
15434         */
15435        final boolean existing;
15436
15437        final String resolvedPath;
15438        final File resolvedFile;
15439
15440        static OriginInfo fromNothing() {
15441            return new OriginInfo(null, null, false, false);
15442        }
15443
15444        static OriginInfo fromUntrustedFile(File file) {
15445            return new OriginInfo(file, null, false, false);
15446        }
15447
15448        static OriginInfo fromExistingFile(File file) {
15449            return new OriginInfo(file, null, false, true);
15450        }
15451
15452        static OriginInfo fromStagedFile(File file) {
15453            return new OriginInfo(file, null, true, false);
15454        }
15455
15456        static OriginInfo fromStagedContainer(String cid) {
15457            return new OriginInfo(null, cid, true, false);
15458        }
15459
15460        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
15461            this.file = file;
15462            this.cid = cid;
15463            this.staged = staged;
15464            this.existing = existing;
15465
15466            if (cid != null) {
15467                resolvedPath = PackageHelper.getSdDir(cid);
15468                resolvedFile = new File(resolvedPath);
15469            } else if (file != null) {
15470                resolvedPath = file.getAbsolutePath();
15471                resolvedFile = file;
15472            } else {
15473                resolvedPath = null;
15474                resolvedFile = null;
15475            }
15476        }
15477    }
15478
15479    static class MoveInfo {
15480        final int moveId;
15481        final String fromUuid;
15482        final String toUuid;
15483        final String packageName;
15484        final String dataAppName;
15485        final int appId;
15486        final String seinfo;
15487        final int targetSdkVersion;
15488
15489        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
15490                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
15491            this.moveId = moveId;
15492            this.fromUuid = fromUuid;
15493            this.toUuid = toUuid;
15494            this.packageName = packageName;
15495            this.dataAppName = dataAppName;
15496            this.appId = appId;
15497            this.seinfo = seinfo;
15498            this.targetSdkVersion = targetSdkVersion;
15499        }
15500    }
15501
15502    static class VerificationInfo {
15503        /** A constant used to indicate that a uid value is not present. */
15504        public static final int NO_UID = -1;
15505
15506        /** URI referencing where the package was downloaded from. */
15507        final Uri originatingUri;
15508
15509        /** HTTP referrer URI associated with the originatingURI. */
15510        final Uri referrer;
15511
15512        /** UID of the application that the install request originated from. */
15513        final int originatingUid;
15514
15515        /** UID of application requesting the install */
15516        final int installerUid;
15517
15518        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
15519            this.originatingUri = originatingUri;
15520            this.referrer = referrer;
15521            this.originatingUid = originatingUid;
15522            this.installerUid = installerUid;
15523        }
15524    }
15525
15526    class InstallParams extends HandlerParams {
15527        final OriginInfo origin;
15528        final MoveInfo move;
15529        final IPackageInstallObserver2 observer;
15530        int installFlags;
15531        final String installerPackageName;
15532        final String volumeUuid;
15533        private InstallArgs mArgs;
15534        private int mRet;
15535        final String packageAbiOverride;
15536        final String[] grantedRuntimePermissions;
15537        final VerificationInfo verificationInfo;
15538        final Certificate[][] certificates;
15539        final int installReason;
15540
15541        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15542                int installFlags, String installerPackageName, String volumeUuid,
15543                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
15544                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
15545            super(user);
15546            this.origin = origin;
15547            this.move = move;
15548            this.observer = observer;
15549            this.installFlags = installFlags;
15550            this.installerPackageName = installerPackageName;
15551            this.volumeUuid = volumeUuid;
15552            this.verificationInfo = verificationInfo;
15553            this.packageAbiOverride = packageAbiOverride;
15554            this.grantedRuntimePermissions = grantedPermissions;
15555            this.certificates = certificates;
15556            this.installReason = installReason;
15557        }
15558
15559        @Override
15560        public String toString() {
15561            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
15562                    + " file=" + origin.file + " cid=" + origin.cid + "}";
15563        }
15564
15565        private int installLocationPolicy(PackageInfoLite pkgLite) {
15566            String packageName = pkgLite.packageName;
15567            int installLocation = pkgLite.installLocation;
15568            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15569            // reader
15570            synchronized (mPackages) {
15571                // Currently installed package which the new package is attempting to replace or
15572                // null if no such package is installed.
15573                PackageParser.Package installedPkg = mPackages.get(packageName);
15574                // Package which currently owns the data which the new package will own if installed.
15575                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
15576                // will be null whereas dataOwnerPkg will contain information about the package
15577                // which was uninstalled while keeping its data.
15578                PackageParser.Package dataOwnerPkg = installedPkg;
15579                if (dataOwnerPkg  == null) {
15580                    PackageSetting ps = mSettings.mPackages.get(packageName);
15581                    if (ps != null) {
15582                        dataOwnerPkg = ps.pkg;
15583                    }
15584                }
15585
15586                if (dataOwnerPkg != null) {
15587                    // If installed, the package will get access to data left on the device by its
15588                    // predecessor. As a security measure, this is permited only if this is not a
15589                    // version downgrade or if the predecessor package is marked as debuggable and
15590                    // a downgrade is explicitly requested.
15591                    //
15592                    // On debuggable platform builds, downgrades are permitted even for
15593                    // non-debuggable packages to make testing easier. Debuggable platform builds do
15594                    // not offer security guarantees and thus it's OK to disable some security
15595                    // mechanisms to make debugging/testing easier on those builds. However, even on
15596                    // debuggable builds downgrades of packages are permitted only if requested via
15597                    // installFlags. This is because we aim to keep the behavior of debuggable
15598                    // platform builds as close as possible to the behavior of non-debuggable
15599                    // platform builds.
15600                    final boolean downgradeRequested =
15601                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
15602                    final boolean packageDebuggable =
15603                                (dataOwnerPkg.applicationInfo.flags
15604                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
15605                    final boolean downgradePermitted =
15606                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
15607                    if (!downgradePermitted) {
15608                        try {
15609                            checkDowngrade(dataOwnerPkg, pkgLite);
15610                        } catch (PackageManagerException e) {
15611                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
15612                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
15613                        }
15614                    }
15615                }
15616
15617                if (installedPkg != null) {
15618                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15619                        // Check for updated system application.
15620                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15621                            if (onSd) {
15622                                Slog.w(TAG, "Cannot install update to system app on sdcard");
15623                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
15624                            }
15625                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15626                        } else {
15627                            if (onSd) {
15628                                // Install flag overrides everything.
15629                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15630                            }
15631                            // If current upgrade specifies particular preference
15632                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
15633                                // Application explicitly specified internal.
15634                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15635                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
15636                                // App explictly prefers external. Let policy decide
15637                            } else {
15638                                // Prefer previous location
15639                                if (isExternal(installedPkg)) {
15640                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15641                                }
15642                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15643                            }
15644                        }
15645                    } else {
15646                        // Invalid install. Return error code
15647                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
15648                    }
15649                }
15650            }
15651            // All the special cases have been taken care of.
15652            // Return result based on recommended install location.
15653            if (onSd) {
15654                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15655            }
15656            return pkgLite.recommendedInstallLocation;
15657        }
15658
15659        /*
15660         * Invoke remote method to get package information and install
15661         * location values. Override install location based on default
15662         * policy if needed and then create install arguments based
15663         * on the install location.
15664         */
15665        public void handleStartCopy() throws RemoteException {
15666            int ret = PackageManager.INSTALL_SUCCEEDED;
15667
15668            // If we're already staged, we've firmly committed to an install location
15669            if (origin.staged) {
15670                if (origin.file != null) {
15671                    installFlags |= PackageManager.INSTALL_INTERNAL;
15672                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15673                } else if (origin.cid != null) {
15674                    installFlags |= PackageManager.INSTALL_EXTERNAL;
15675                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
15676                } else {
15677                    throw new IllegalStateException("Invalid stage location");
15678                }
15679            }
15680
15681            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15682            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
15683            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15684            PackageInfoLite pkgLite = null;
15685
15686            if (onInt && onSd) {
15687                // Check if both bits are set.
15688                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
15689                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15690            } else if (onSd && ephemeral) {
15691                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
15692                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15693            } else {
15694                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
15695                        packageAbiOverride);
15696
15697                if (DEBUG_EPHEMERAL && ephemeral) {
15698                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
15699                }
15700
15701                /*
15702                 * If we have too little free space, try to free cache
15703                 * before giving up.
15704                 */
15705                if (!origin.staged && pkgLite.recommendedInstallLocation
15706                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15707                    // TODO: focus freeing disk space on the target device
15708                    final StorageManager storage = StorageManager.from(mContext);
15709                    final long lowThreshold = storage.getStorageLowBytes(
15710                            Environment.getDataDirectory());
15711
15712                    final long sizeBytes = mContainerService.calculateInstalledSize(
15713                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
15714
15715                    try {
15716                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
15717                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
15718                                installFlags, packageAbiOverride);
15719                    } catch (InstallerException e) {
15720                        Slog.w(TAG, "Failed to free cache", e);
15721                    }
15722
15723                    /*
15724                     * The cache free must have deleted the file we
15725                     * downloaded to install.
15726                     *
15727                     * TODO: fix the "freeCache" call to not delete
15728                     *       the file we care about.
15729                     */
15730                    if (pkgLite.recommendedInstallLocation
15731                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15732                        pkgLite.recommendedInstallLocation
15733                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
15734                    }
15735                }
15736            }
15737
15738            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15739                int loc = pkgLite.recommendedInstallLocation;
15740                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
15741                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15742                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
15743                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
15744                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15745                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15746                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
15747                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
15748                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15749                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
15750                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
15751                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
15752                } else {
15753                    // Override with defaults if needed.
15754                    loc = installLocationPolicy(pkgLite);
15755                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
15756                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
15757                    } else if (!onSd && !onInt) {
15758                        // Override install location with flags
15759                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
15760                            // Set the flag to install on external media.
15761                            installFlags |= PackageManager.INSTALL_EXTERNAL;
15762                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
15763                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
15764                            if (DEBUG_EPHEMERAL) {
15765                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
15766                            }
15767                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
15768                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
15769                                    |PackageManager.INSTALL_INTERNAL);
15770                        } else {
15771                            // Make sure the flag for installing on external
15772                            // media is unset
15773                            installFlags |= PackageManager.INSTALL_INTERNAL;
15774                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15775                        }
15776                    }
15777                }
15778            }
15779
15780            final InstallArgs args = createInstallArgs(this);
15781            mArgs = args;
15782
15783            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15784                // TODO: http://b/22976637
15785                // Apps installed for "all" users use the device owner to verify the app
15786                UserHandle verifierUser = getUser();
15787                if (verifierUser == UserHandle.ALL) {
15788                    verifierUser = UserHandle.SYSTEM;
15789                }
15790
15791                /*
15792                 * Determine if we have any installed package verifiers. If we
15793                 * do, then we'll defer to them to verify the packages.
15794                 */
15795                final int requiredUid = mRequiredVerifierPackage == null ? -1
15796                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15797                                verifierUser.getIdentifier());
15798                final int installerUid =
15799                        verificationInfo == null ? -1 : verificationInfo.installerUid;
15800                if (!origin.existing && requiredUid != -1
15801                        && isVerificationEnabled(
15802                                verifierUser.getIdentifier(), installFlags, installerUid)) {
15803                    final Intent verification = new Intent(
15804                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
15805                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
15806                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
15807                            PACKAGE_MIME_TYPE);
15808                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15809
15810                    // Query all live verifiers based on current user state
15811                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
15812                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
15813
15814                    if (DEBUG_VERIFY) {
15815                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
15816                                + verification.toString() + " with " + pkgLite.verifiers.length
15817                                + " optional verifiers");
15818                    }
15819
15820                    final int verificationId = mPendingVerificationToken++;
15821
15822                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15823
15824                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
15825                            installerPackageName);
15826
15827                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
15828                            installFlags);
15829
15830                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
15831                            pkgLite.packageName);
15832
15833                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
15834                            pkgLite.versionCode);
15835
15836                    if (verificationInfo != null) {
15837                        if (verificationInfo.originatingUri != null) {
15838                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
15839                                    verificationInfo.originatingUri);
15840                        }
15841                        if (verificationInfo.referrer != null) {
15842                            verification.putExtra(Intent.EXTRA_REFERRER,
15843                                    verificationInfo.referrer);
15844                        }
15845                        if (verificationInfo.originatingUid >= 0) {
15846                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
15847                                    verificationInfo.originatingUid);
15848                        }
15849                        if (verificationInfo.installerUid >= 0) {
15850                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
15851                                    verificationInfo.installerUid);
15852                        }
15853                    }
15854
15855                    final PackageVerificationState verificationState = new PackageVerificationState(
15856                            requiredUid, args);
15857
15858                    mPendingVerification.append(verificationId, verificationState);
15859
15860                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
15861                            receivers, verificationState);
15862
15863                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
15864                    final long idleDuration = getVerificationTimeout();
15865
15866                    /*
15867                     * If any sufficient verifiers were listed in the package
15868                     * manifest, attempt to ask them.
15869                     */
15870                    if (sufficientVerifiers != null) {
15871                        final int N = sufficientVerifiers.size();
15872                        if (N == 0) {
15873                            Slog.i(TAG, "Additional verifiers required, but none installed.");
15874                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
15875                        } else {
15876                            for (int i = 0; i < N; i++) {
15877                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
15878                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15879                                        verifierComponent.getPackageName(), idleDuration,
15880                                        verifierUser.getIdentifier(), false, "package verifier");
15881
15882                                final Intent sufficientIntent = new Intent(verification);
15883                                sufficientIntent.setComponent(verifierComponent);
15884                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
15885                            }
15886                        }
15887                    }
15888
15889                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
15890                            mRequiredVerifierPackage, receivers);
15891                    if (ret == PackageManager.INSTALL_SUCCEEDED
15892                            && mRequiredVerifierPackage != null) {
15893                        Trace.asyncTraceBegin(
15894                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
15895                        /*
15896                         * Send the intent to the required verification agent,
15897                         * but only start the verification timeout after the
15898                         * target BroadcastReceivers have run.
15899                         */
15900                        verification.setComponent(requiredVerifierComponent);
15901                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15902                                mRequiredVerifierPackage, idleDuration,
15903                                verifierUser.getIdentifier(), false, "package verifier");
15904                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
15905                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15906                                new BroadcastReceiver() {
15907                                    @Override
15908                                    public void onReceive(Context context, Intent intent) {
15909                                        final Message msg = mHandler
15910                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
15911                                        msg.arg1 = verificationId;
15912                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
15913                                    }
15914                                }, null, 0, null, null);
15915
15916                        /*
15917                         * We don't want the copy to proceed until verification
15918                         * succeeds, so null out this field.
15919                         */
15920                        mArgs = null;
15921                    }
15922                } else {
15923                    /*
15924                     * No package verification is enabled, so immediately start
15925                     * the remote call to initiate copy using temporary file.
15926                     */
15927                    ret = args.copyApk(mContainerService, true);
15928                }
15929            }
15930
15931            mRet = ret;
15932        }
15933
15934        @Override
15935        void handleReturnCode() {
15936            // If mArgs is null, then MCS couldn't be reached. When it
15937            // reconnects, it will try again to install. At that point, this
15938            // will succeed.
15939            if (mArgs != null) {
15940                processPendingInstall(mArgs, mRet);
15941            }
15942        }
15943
15944        @Override
15945        void handleServiceError() {
15946            mArgs = createInstallArgs(this);
15947            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15948        }
15949
15950        public boolean isForwardLocked() {
15951            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15952        }
15953    }
15954
15955    /**
15956     * Used during creation of InstallArgs
15957     *
15958     * @param installFlags package installation flags
15959     * @return true if should be installed on external storage
15960     */
15961    private static boolean installOnExternalAsec(int installFlags) {
15962        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
15963            return false;
15964        }
15965        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
15966            return true;
15967        }
15968        return false;
15969    }
15970
15971    /**
15972     * Used during creation of InstallArgs
15973     *
15974     * @param installFlags package installation flags
15975     * @return true if should be installed as forward locked
15976     */
15977    private static boolean installForwardLocked(int installFlags) {
15978        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15979    }
15980
15981    private InstallArgs createInstallArgs(InstallParams params) {
15982        if (params.move != null) {
15983            return new MoveInstallArgs(params);
15984        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
15985            return new AsecInstallArgs(params);
15986        } else {
15987            return new FileInstallArgs(params);
15988        }
15989    }
15990
15991    /**
15992     * Create args that describe an existing installed package. Typically used
15993     * when cleaning up old installs, or used as a move source.
15994     */
15995    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
15996            String resourcePath, String[] instructionSets) {
15997        final boolean isInAsec;
15998        if (installOnExternalAsec(installFlags)) {
15999            /* Apps on SD card are always in ASEC containers. */
16000            isInAsec = true;
16001        } else if (installForwardLocked(installFlags)
16002                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
16003            /*
16004             * Forward-locked apps are only in ASEC containers if they're the
16005             * new style
16006             */
16007            isInAsec = true;
16008        } else {
16009            isInAsec = false;
16010        }
16011
16012        if (isInAsec) {
16013            return new AsecInstallArgs(codePath, instructionSets,
16014                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
16015        } else {
16016            return new FileInstallArgs(codePath, resourcePath, instructionSets);
16017        }
16018    }
16019
16020    static abstract class InstallArgs {
16021        /** @see InstallParams#origin */
16022        final OriginInfo origin;
16023        /** @see InstallParams#move */
16024        final MoveInfo move;
16025
16026        final IPackageInstallObserver2 observer;
16027        // Always refers to PackageManager flags only
16028        final int installFlags;
16029        final String installerPackageName;
16030        final String volumeUuid;
16031        final UserHandle user;
16032        final String abiOverride;
16033        final String[] installGrantPermissions;
16034        /** If non-null, drop an async trace when the install completes */
16035        final String traceMethod;
16036        final int traceCookie;
16037        final Certificate[][] certificates;
16038        final int installReason;
16039
16040        // The list of instruction sets supported by this app. This is currently
16041        // only used during the rmdex() phase to clean up resources. We can get rid of this
16042        // if we move dex files under the common app path.
16043        /* nullable */ String[] instructionSets;
16044
16045        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
16046                int installFlags, String installerPackageName, String volumeUuid,
16047                UserHandle user, String[] instructionSets,
16048                String abiOverride, String[] installGrantPermissions,
16049                String traceMethod, int traceCookie, Certificate[][] certificates,
16050                int installReason) {
16051            this.origin = origin;
16052            this.move = move;
16053            this.installFlags = installFlags;
16054            this.observer = observer;
16055            this.installerPackageName = installerPackageName;
16056            this.volumeUuid = volumeUuid;
16057            this.user = user;
16058            this.instructionSets = instructionSets;
16059            this.abiOverride = abiOverride;
16060            this.installGrantPermissions = installGrantPermissions;
16061            this.traceMethod = traceMethod;
16062            this.traceCookie = traceCookie;
16063            this.certificates = certificates;
16064            this.installReason = installReason;
16065        }
16066
16067        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
16068        abstract int doPreInstall(int status);
16069
16070        /**
16071         * Rename package into final resting place. All paths on the given
16072         * scanned package should be updated to reflect the rename.
16073         */
16074        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
16075        abstract int doPostInstall(int status, int uid);
16076
16077        /** @see PackageSettingBase#codePathString */
16078        abstract String getCodePath();
16079        /** @see PackageSettingBase#resourcePathString */
16080        abstract String getResourcePath();
16081
16082        // Need installer lock especially for dex file removal.
16083        abstract void cleanUpResourcesLI();
16084        abstract boolean doPostDeleteLI(boolean delete);
16085
16086        /**
16087         * Called before the source arguments are copied. This is used mostly
16088         * for MoveParams when it needs to read the source file to put it in the
16089         * destination.
16090         */
16091        int doPreCopy() {
16092            return PackageManager.INSTALL_SUCCEEDED;
16093        }
16094
16095        /**
16096         * Called after the source arguments are copied. This is used mostly for
16097         * MoveParams when it needs to read the source file to put it in the
16098         * destination.
16099         */
16100        int doPostCopy(int uid) {
16101            return PackageManager.INSTALL_SUCCEEDED;
16102        }
16103
16104        protected boolean isFwdLocked() {
16105            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16106        }
16107
16108        protected boolean isExternalAsec() {
16109            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16110        }
16111
16112        protected boolean isEphemeral() {
16113            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16114        }
16115
16116        UserHandle getUser() {
16117            return user;
16118        }
16119    }
16120
16121    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
16122        if (!allCodePaths.isEmpty()) {
16123            if (instructionSets == null) {
16124                throw new IllegalStateException("instructionSet == null");
16125            }
16126            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
16127            for (String codePath : allCodePaths) {
16128                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
16129                    try {
16130                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
16131                    } catch (InstallerException ignored) {
16132                    }
16133                }
16134            }
16135        }
16136    }
16137
16138    /**
16139     * Logic to handle installation of non-ASEC applications, including copying
16140     * and renaming logic.
16141     */
16142    class FileInstallArgs extends InstallArgs {
16143        private File codeFile;
16144        private File resourceFile;
16145
16146        // Example topology:
16147        // /data/app/com.example/base.apk
16148        // /data/app/com.example/split_foo.apk
16149        // /data/app/com.example/lib/arm/libfoo.so
16150        // /data/app/com.example/lib/arm64/libfoo.so
16151        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
16152
16153        /** New install */
16154        FileInstallArgs(InstallParams params) {
16155            super(params.origin, params.move, params.observer, params.installFlags,
16156                    params.installerPackageName, params.volumeUuid,
16157                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
16158                    params.grantedRuntimePermissions,
16159                    params.traceMethod, params.traceCookie, params.certificates,
16160                    params.installReason);
16161            if (isFwdLocked()) {
16162                throw new IllegalArgumentException("Forward locking only supported in ASEC");
16163            }
16164        }
16165
16166        /** Existing install */
16167        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
16168            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
16169                    null, null, null, 0, null /*certificates*/,
16170                    PackageManager.INSTALL_REASON_UNKNOWN);
16171            this.codeFile = (codePath != null) ? new File(codePath) : null;
16172            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
16173        }
16174
16175        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16176            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
16177            try {
16178                return doCopyApk(imcs, temp);
16179            } finally {
16180                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16181            }
16182        }
16183
16184        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16185            if (origin.staged) {
16186                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
16187                codeFile = origin.file;
16188                resourceFile = origin.file;
16189                return PackageManager.INSTALL_SUCCEEDED;
16190            }
16191
16192            try {
16193                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16194                final File tempDir =
16195                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
16196                codeFile = tempDir;
16197                resourceFile = tempDir;
16198            } catch (IOException e) {
16199                Slog.w(TAG, "Failed to create copy file: " + e);
16200                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
16201            }
16202
16203            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
16204                @Override
16205                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
16206                    if (!FileUtils.isValidExtFilename(name)) {
16207                        throw new IllegalArgumentException("Invalid filename: " + name);
16208                    }
16209                    try {
16210                        final File file = new File(codeFile, name);
16211                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
16212                                O_RDWR | O_CREAT, 0644);
16213                        Os.chmod(file.getAbsolutePath(), 0644);
16214                        return new ParcelFileDescriptor(fd);
16215                    } catch (ErrnoException e) {
16216                        throw new RemoteException("Failed to open: " + e.getMessage());
16217                    }
16218                }
16219            };
16220
16221            int ret = PackageManager.INSTALL_SUCCEEDED;
16222            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
16223            if (ret != PackageManager.INSTALL_SUCCEEDED) {
16224                Slog.e(TAG, "Failed to copy package");
16225                return ret;
16226            }
16227
16228            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
16229            NativeLibraryHelper.Handle handle = null;
16230            try {
16231                handle = NativeLibraryHelper.Handle.create(codeFile);
16232                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
16233                        abiOverride);
16234            } catch (IOException e) {
16235                Slog.e(TAG, "Copying native libraries failed", e);
16236                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16237            } finally {
16238                IoUtils.closeQuietly(handle);
16239            }
16240
16241            return ret;
16242        }
16243
16244        int doPreInstall(int status) {
16245            if (status != PackageManager.INSTALL_SUCCEEDED) {
16246                cleanUp();
16247            }
16248            return status;
16249        }
16250
16251        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16252            if (status != PackageManager.INSTALL_SUCCEEDED) {
16253                cleanUp();
16254                return false;
16255            }
16256
16257            final File targetDir = codeFile.getParentFile();
16258            final File beforeCodeFile = codeFile;
16259            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
16260
16261            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
16262            try {
16263                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
16264            } catch (ErrnoException e) {
16265                Slog.w(TAG, "Failed to rename", e);
16266                return false;
16267            }
16268
16269            if (!SELinux.restoreconRecursive(afterCodeFile)) {
16270                Slog.w(TAG, "Failed to restorecon");
16271                return false;
16272            }
16273
16274            // Reflect the rename internally
16275            codeFile = afterCodeFile;
16276            resourceFile = afterCodeFile;
16277
16278            // Reflect the rename in scanned details
16279            pkg.setCodePath(afterCodeFile.getAbsolutePath());
16280            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16281                    afterCodeFile, pkg.baseCodePath));
16282            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16283                    afterCodeFile, pkg.splitCodePaths));
16284
16285            // Reflect the rename in app info
16286            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16287            pkg.setApplicationInfoCodePath(pkg.codePath);
16288            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16289            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16290            pkg.setApplicationInfoResourcePath(pkg.codePath);
16291            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16292            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16293
16294            return true;
16295        }
16296
16297        int doPostInstall(int status, int uid) {
16298            if (status != PackageManager.INSTALL_SUCCEEDED) {
16299                cleanUp();
16300            }
16301            return status;
16302        }
16303
16304        @Override
16305        String getCodePath() {
16306            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16307        }
16308
16309        @Override
16310        String getResourcePath() {
16311            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16312        }
16313
16314        private boolean cleanUp() {
16315            if (codeFile == null || !codeFile.exists()) {
16316                return false;
16317            }
16318
16319            removeCodePathLI(codeFile);
16320
16321            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
16322                resourceFile.delete();
16323            }
16324
16325            return true;
16326        }
16327
16328        void cleanUpResourcesLI() {
16329            // Try enumerating all code paths before deleting
16330            List<String> allCodePaths = Collections.EMPTY_LIST;
16331            if (codeFile != null && codeFile.exists()) {
16332                try {
16333                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16334                    allCodePaths = pkg.getAllCodePaths();
16335                } catch (PackageParserException e) {
16336                    // Ignored; we tried our best
16337                }
16338            }
16339
16340            cleanUp();
16341            removeDexFiles(allCodePaths, instructionSets);
16342        }
16343
16344        boolean doPostDeleteLI(boolean delete) {
16345            // XXX err, shouldn't we respect the delete flag?
16346            cleanUpResourcesLI();
16347            return true;
16348        }
16349    }
16350
16351    private boolean isAsecExternal(String cid) {
16352        final String asecPath = PackageHelper.getSdFilesystem(cid);
16353        return !asecPath.startsWith(mAsecInternalPath);
16354    }
16355
16356    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
16357            PackageManagerException {
16358        if (copyRet < 0) {
16359            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
16360                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
16361                throw new PackageManagerException(copyRet, message);
16362            }
16363        }
16364    }
16365
16366    /**
16367     * Extract the StorageManagerService "container ID" from the full code path of an
16368     * .apk.
16369     */
16370    static String cidFromCodePath(String fullCodePath) {
16371        int eidx = fullCodePath.lastIndexOf("/");
16372        String subStr1 = fullCodePath.substring(0, eidx);
16373        int sidx = subStr1.lastIndexOf("/");
16374        return subStr1.substring(sidx+1, eidx);
16375    }
16376
16377    /**
16378     * Logic to handle installation of ASEC applications, including copying and
16379     * renaming logic.
16380     */
16381    class AsecInstallArgs extends InstallArgs {
16382        static final String RES_FILE_NAME = "pkg.apk";
16383        static final String PUBLIC_RES_FILE_NAME = "res.zip";
16384
16385        String cid;
16386        String packagePath;
16387        String resourcePath;
16388
16389        /** New install */
16390        AsecInstallArgs(InstallParams params) {
16391            super(params.origin, params.move, params.observer, params.installFlags,
16392                    params.installerPackageName, params.volumeUuid,
16393                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
16394                    params.grantedRuntimePermissions,
16395                    params.traceMethod, params.traceCookie, params.certificates,
16396                    params.installReason);
16397        }
16398
16399        /** Existing install */
16400        AsecInstallArgs(String fullCodePath, String[] instructionSets,
16401                        boolean isExternal, boolean isForwardLocked) {
16402            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
16403                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
16404                    instructionSets, null, null, null, 0, null /*certificates*/,
16405                    PackageManager.INSTALL_REASON_UNKNOWN);
16406            // Hackily pretend we're still looking at a full code path
16407            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
16408                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
16409            }
16410
16411            // Extract cid from fullCodePath
16412            int eidx = fullCodePath.lastIndexOf("/");
16413            String subStr1 = fullCodePath.substring(0, eidx);
16414            int sidx = subStr1.lastIndexOf("/");
16415            cid = subStr1.substring(sidx+1, eidx);
16416            setMountPath(subStr1);
16417        }
16418
16419        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
16420            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
16421                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
16422                    instructionSets, null, null, null, 0, null /*certificates*/,
16423                    PackageManager.INSTALL_REASON_UNKNOWN);
16424            this.cid = cid;
16425            setMountPath(PackageHelper.getSdDir(cid));
16426        }
16427
16428        void createCopyFile() {
16429            cid = mInstallerService.allocateExternalStageCidLegacy();
16430        }
16431
16432        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16433            if (origin.staged && origin.cid != null) {
16434                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
16435                cid = origin.cid;
16436                setMountPath(PackageHelper.getSdDir(cid));
16437                return PackageManager.INSTALL_SUCCEEDED;
16438            }
16439
16440            if (temp) {
16441                createCopyFile();
16442            } else {
16443                /*
16444                 * Pre-emptively destroy the container since it's destroyed if
16445                 * copying fails due to it existing anyway.
16446                 */
16447                PackageHelper.destroySdDir(cid);
16448            }
16449
16450            final String newMountPath = imcs.copyPackageToContainer(
16451                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
16452                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
16453
16454            if (newMountPath != null) {
16455                setMountPath(newMountPath);
16456                return PackageManager.INSTALL_SUCCEEDED;
16457            } else {
16458                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16459            }
16460        }
16461
16462        @Override
16463        String getCodePath() {
16464            return packagePath;
16465        }
16466
16467        @Override
16468        String getResourcePath() {
16469            return resourcePath;
16470        }
16471
16472        int doPreInstall(int status) {
16473            if (status != PackageManager.INSTALL_SUCCEEDED) {
16474                // Destroy container
16475                PackageHelper.destroySdDir(cid);
16476            } else {
16477                boolean mounted = PackageHelper.isContainerMounted(cid);
16478                if (!mounted) {
16479                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
16480                            Process.SYSTEM_UID);
16481                    if (newMountPath != null) {
16482                        setMountPath(newMountPath);
16483                    } else {
16484                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16485                    }
16486                }
16487            }
16488            return status;
16489        }
16490
16491        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16492            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
16493            String newMountPath = null;
16494            if (PackageHelper.isContainerMounted(cid)) {
16495                // Unmount the container
16496                if (!PackageHelper.unMountSdDir(cid)) {
16497                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
16498                    return false;
16499                }
16500            }
16501            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
16502                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
16503                        " which might be stale. Will try to clean up.");
16504                // Clean up the stale container and proceed to recreate.
16505                if (!PackageHelper.destroySdDir(newCacheId)) {
16506                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
16507                    return false;
16508                }
16509                // Successfully cleaned up stale container. Try to rename again.
16510                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
16511                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
16512                            + " inspite of cleaning it up.");
16513                    return false;
16514                }
16515            }
16516            if (!PackageHelper.isContainerMounted(newCacheId)) {
16517                Slog.w(TAG, "Mounting container " + newCacheId);
16518                newMountPath = PackageHelper.mountSdDir(newCacheId,
16519                        getEncryptKey(), Process.SYSTEM_UID);
16520            } else {
16521                newMountPath = PackageHelper.getSdDir(newCacheId);
16522            }
16523            if (newMountPath == null) {
16524                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
16525                return false;
16526            }
16527            Log.i(TAG, "Succesfully renamed " + cid +
16528                    " to " + newCacheId +
16529                    " at new path: " + newMountPath);
16530            cid = newCacheId;
16531
16532            final File beforeCodeFile = new File(packagePath);
16533            setMountPath(newMountPath);
16534            final File afterCodeFile = new File(packagePath);
16535
16536            // Reflect the rename in scanned details
16537            pkg.setCodePath(afterCodeFile.getAbsolutePath());
16538            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16539                    afterCodeFile, pkg.baseCodePath));
16540            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16541                    afterCodeFile, pkg.splitCodePaths));
16542
16543            // Reflect the rename in app info
16544            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16545            pkg.setApplicationInfoCodePath(pkg.codePath);
16546            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16547            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16548            pkg.setApplicationInfoResourcePath(pkg.codePath);
16549            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16550            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16551
16552            return true;
16553        }
16554
16555        private void setMountPath(String mountPath) {
16556            final File mountFile = new File(mountPath);
16557
16558            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
16559            if (monolithicFile.exists()) {
16560                packagePath = monolithicFile.getAbsolutePath();
16561                if (isFwdLocked()) {
16562                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
16563                } else {
16564                    resourcePath = packagePath;
16565                }
16566            } else {
16567                packagePath = mountFile.getAbsolutePath();
16568                resourcePath = packagePath;
16569            }
16570        }
16571
16572        int doPostInstall(int status, int uid) {
16573            if (status != PackageManager.INSTALL_SUCCEEDED) {
16574                cleanUp();
16575            } else {
16576                final int groupOwner;
16577                final String protectedFile;
16578                if (isFwdLocked()) {
16579                    groupOwner = UserHandle.getSharedAppGid(uid);
16580                    protectedFile = RES_FILE_NAME;
16581                } else {
16582                    groupOwner = -1;
16583                    protectedFile = null;
16584                }
16585
16586                if (uid < Process.FIRST_APPLICATION_UID
16587                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
16588                    Slog.e(TAG, "Failed to finalize " + cid);
16589                    PackageHelper.destroySdDir(cid);
16590                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16591                }
16592
16593                boolean mounted = PackageHelper.isContainerMounted(cid);
16594                if (!mounted) {
16595                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
16596                }
16597            }
16598            return status;
16599        }
16600
16601        private void cleanUp() {
16602            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
16603
16604            // Destroy secure container
16605            PackageHelper.destroySdDir(cid);
16606        }
16607
16608        private List<String> getAllCodePaths() {
16609            final File codeFile = new File(getCodePath());
16610            if (codeFile != null && codeFile.exists()) {
16611                try {
16612                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16613                    return pkg.getAllCodePaths();
16614                } catch (PackageParserException e) {
16615                    // Ignored; we tried our best
16616                }
16617            }
16618            return Collections.EMPTY_LIST;
16619        }
16620
16621        void cleanUpResourcesLI() {
16622            // Enumerate all code paths before deleting
16623            cleanUpResourcesLI(getAllCodePaths());
16624        }
16625
16626        private void cleanUpResourcesLI(List<String> allCodePaths) {
16627            cleanUp();
16628            removeDexFiles(allCodePaths, instructionSets);
16629        }
16630
16631        String getPackageName() {
16632            return getAsecPackageName(cid);
16633        }
16634
16635        boolean doPostDeleteLI(boolean delete) {
16636            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
16637            final List<String> allCodePaths = getAllCodePaths();
16638            boolean mounted = PackageHelper.isContainerMounted(cid);
16639            if (mounted) {
16640                // Unmount first
16641                if (PackageHelper.unMountSdDir(cid)) {
16642                    mounted = false;
16643                }
16644            }
16645            if (!mounted && delete) {
16646                cleanUpResourcesLI(allCodePaths);
16647            }
16648            return !mounted;
16649        }
16650
16651        @Override
16652        int doPreCopy() {
16653            if (isFwdLocked()) {
16654                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
16655                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
16656                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16657                }
16658            }
16659
16660            return PackageManager.INSTALL_SUCCEEDED;
16661        }
16662
16663        @Override
16664        int doPostCopy(int uid) {
16665            if (isFwdLocked()) {
16666                if (uid < Process.FIRST_APPLICATION_UID
16667                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
16668                                RES_FILE_NAME)) {
16669                    Slog.e(TAG, "Failed to finalize " + cid);
16670                    PackageHelper.destroySdDir(cid);
16671                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16672                }
16673            }
16674
16675            return PackageManager.INSTALL_SUCCEEDED;
16676        }
16677    }
16678
16679    /**
16680     * Logic to handle movement of existing installed applications.
16681     */
16682    class MoveInstallArgs extends InstallArgs {
16683        private File codeFile;
16684        private File resourceFile;
16685
16686        /** New install */
16687        MoveInstallArgs(InstallParams params) {
16688            super(params.origin, params.move, params.observer, params.installFlags,
16689                    params.installerPackageName, params.volumeUuid,
16690                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
16691                    params.grantedRuntimePermissions,
16692                    params.traceMethod, params.traceCookie, params.certificates,
16693                    params.installReason);
16694        }
16695
16696        int copyApk(IMediaContainerService imcs, boolean temp) {
16697            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
16698                    + move.fromUuid + " to " + move.toUuid);
16699            synchronized (mInstaller) {
16700                try {
16701                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
16702                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
16703                } catch (InstallerException e) {
16704                    Slog.w(TAG, "Failed to move app", e);
16705                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16706                }
16707            }
16708
16709            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
16710            resourceFile = codeFile;
16711            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
16712
16713            return PackageManager.INSTALL_SUCCEEDED;
16714        }
16715
16716        int doPreInstall(int status) {
16717            if (status != PackageManager.INSTALL_SUCCEEDED) {
16718                cleanUp(move.toUuid);
16719            }
16720            return status;
16721        }
16722
16723        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16724            if (status != PackageManager.INSTALL_SUCCEEDED) {
16725                cleanUp(move.toUuid);
16726                return false;
16727            }
16728
16729            // Reflect the move in app info
16730            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16731            pkg.setApplicationInfoCodePath(pkg.codePath);
16732            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16733            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16734            pkg.setApplicationInfoResourcePath(pkg.codePath);
16735            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16736            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16737
16738            return true;
16739        }
16740
16741        int doPostInstall(int status, int uid) {
16742            if (status == PackageManager.INSTALL_SUCCEEDED) {
16743                cleanUp(move.fromUuid);
16744            } else {
16745                cleanUp(move.toUuid);
16746            }
16747            return status;
16748        }
16749
16750        @Override
16751        String getCodePath() {
16752            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16753        }
16754
16755        @Override
16756        String getResourcePath() {
16757            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16758        }
16759
16760        private boolean cleanUp(String volumeUuid) {
16761            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
16762                    move.dataAppName);
16763            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
16764            final int[] userIds = sUserManager.getUserIds();
16765            synchronized (mInstallLock) {
16766                // Clean up both app data and code
16767                // All package moves are frozen until finished
16768                for (int userId : userIds) {
16769                    try {
16770                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
16771                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
16772                    } catch (InstallerException e) {
16773                        Slog.w(TAG, String.valueOf(e));
16774                    }
16775                }
16776                removeCodePathLI(codeFile);
16777            }
16778            return true;
16779        }
16780
16781        void cleanUpResourcesLI() {
16782            throw new UnsupportedOperationException();
16783        }
16784
16785        boolean doPostDeleteLI(boolean delete) {
16786            throw new UnsupportedOperationException();
16787        }
16788    }
16789
16790    static String getAsecPackageName(String packageCid) {
16791        int idx = packageCid.lastIndexOf("-");
16792        if (idx == -1) {
16793            return packageCid;
16794        }
16795        return packageCid.substring(0, idx);
16796    }
16797
16798    // Utility method used to create code paths based on package name and available index.
16799    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
16800        String idxStr = "";
16801        int idx = 1;
16802        // Fall back to default value of idx=1 if prefix is not
16803        // part of oldCodePath
16804        if (oldCodePath != null) {
16805            String subStr = oldCodePath;
16806            // Drop the suffix right away
16807            if (suffix != null && subStr.endsWith(suffix)) {
16808                subStr = subStr.substring(0, subStr.length() - suffix.length());
16809            }
16810            // If oldCodePath already contains prefix find out the
16811            // ending index to either increment or decrement.
16812            int sidx = subStr.lastIndexOf(prefix);
16813            if (sidx != -1) {
16814                subStr = subStr.substring(sidx + prefix.length());
16815                if (subStr != null) {
16816                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
16817                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
16818                    }
16819                    try {
16820                        idx = Integer.parseInt(subStr);
16821                        if (idx <= 1) {
16822                            idx++;
16823                        } else {
16824                            idx--;
16825                        }
16826                    } catch(NumberFormatException e) {
16827                    }
16828                }
16829            }
16830        }
16831        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
16832        return prefix + idxStr;
16833    }
16834
16835    private File getNextCodePath(File targetDir, String packageName) {
16836        File result;
16837        SecureRandom random = new SecureRandom();
16838        byte[] bytes = new byte[16];
16839        do {
16840            random.nextBytes(bytes);
16841            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
16842            result = new File(targetDir, packageName + "-" + suffix);
16843        } while (result.exists());
16844        return result;
16845    }
16846
16847    // Utility method that returns the relative package path with respect
16848    // to the installation directory. Like say for /data/data/com.test-1.apk
16849    // string com.test-1 is returned.
16850    static String deriveCodePathName(String codePath) {
16851        if (codePath == null) {
16852            return null;
16853        }
16854        final File codeFile = new File(codePath);
16855        final String name = codeFile.getName();
16856        if (codeFile.isDirectory()) {
16857            return name;
16858        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
16859            final int lastDot = name.lastIndexOf('.');
16860            return name.substring(0, lastDot);
16861        } else {
16862            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
16863            return null;
16864        }
16865    }
16866
16867    static class PackageInstalledInfo {
16868        String name;
16869        int uid;
16870        // The set of users that originally had this package installed.
16871        int[] origUsers;
16872        // The set of users that now have this package installed.
16873        int[] newUsers;
16874        PackageParser.Package pkg;
16875        int returnCode;
16876        String returnMsg;
16877        PackageRemovedInfo removedInfo;
16878        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
16879
16880        public void setError(int code, String msg) {
16881            setReturnCode(code);
16882            setReturnMessage(msg);
16883            Slog.w(TAG, msg);
16884        }
16885
16886        public void setError(String msg, PackageParserException e) {
16887            setReturnCode(e.error);
16888            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16889            Slog.w(TAG, msg, e);
16890        }
16891
16892        public void setError(String msg, PackageManagerException e) {
16893            returnCode = e.error;
16894            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16895            Slog.w(TAG, msg, e);
16896        }
16897
16898        public void setReturnCode(int returnCode) {
16899            this.returnCode = returnCode;
16900            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16901            for (int i = 0; i < childCount; i++) {
16902                addedChildPackages.valueAt(i).returnCode = returnCode;
16903            }
16904        }
16905
16906        private void setReturnMessage(String returnMsg) {
16907            this.returnMsg = returnMsg;
16908            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16909            for (int i = 0; i < childCount; i++) {
16910                addedChildPackages.valueAt(i).returnMsg = returnMsg;
16911            }
16912        }
16913
16914        // In some error cases we want to convey more info back to the observer
16915        String origPackage;
16916        String origPermission;
16917    }
16918
16919    /*
16920     * Install a non-existing package.
16921     */
16922    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
16923            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
16924            PackageInstalledInfo res, int installReason) {
16925        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
16926
16927        // Remember this for later, in case we need to rollback this install
16928        String pkgName = pkg.packageName;
16929
16930        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
16931
16932        synchronized(mPackages) {
16933            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
16934            if (renamedPackage != null) {
16935                // A package with the same name is already installed, though
16936                // it has been renamed to an older name.  The package we
16937                // are trying to install should be installed as an update to
16938                // the existing one, but that has not been requested, so bail.
16939                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
16940                        + " without first uninstalling package running as "
16941                        + renamedPackage);
16942                return;
16943            }
16944            if (mPackages.containsKey(pkgName)) {
16945                // Don't allow installation over an existing package with the same name.
16946                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
16947                        + " without first uninstalling.");
16948                return;
16949            }
16950        }
16951
16952        try {
16953            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
16954                    System.currentTimeMillis(), user);
16955
16956            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
16957
16958            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16959                prepareAppDataAfterInstallLIF(newPackage);
16960
16961            } else {
16962                // Remove package from internal structures, but keep around any
16963                // data that might have already existed
16964                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
16965                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
16966            }
16967        } catch (PackageManagerException e) {
16968            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16969        }
16970
16971        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16972    }
16973
16974    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
16975        // Can't rotate keys during boot or if sharedUser.
16976        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
16977                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
16978            return false;
16979        }
16980        // app is using upgradeKeySets; make sure all are valid
16981        KeySetManagerService ksms = mSettings.mKeySetManagerService;
16982        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
16983        for (int i = 0; i < upgradeKeySets.length; i++) {
16984            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
16985                Slog.wtf(TAG, "Package "
16986                         + (oldPs.name != null ? oldPs.name : "<null>")
16987                         + " contains upgrade-key-set reference to unknown key-set: "
16988                         + upgradeKeySets[i]
16989                         + " reverting to signatures check.");
16990                return false;
16991            }
16992        }
16993        return true;
16994    }
16995
16996    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
16997        // Upgrade keysets are being used.  Determine if new package has a superset of the
16998        // required keys.
16999        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
17000        KeySetManagerService ksms = mSettings.mKeySetManagerService;
17001        for (int i = 0; i < upgradeKeySets.length; i++) {
17002            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
17003            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
17004                return true;
17005            }
17006        }
17007        return false;
17008    }
17009
17010    private static void updateDigest(MessageDigest digest, File file) throws IOException {
17011        try (DigestInputStream digestStream =
17012                new DigestInputStream(new FileInputStream(file), digest)) {
17013            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
17014        }
17015    }
17016
17017    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
17018            UserHandle user, String installerPackageName, PackageInstalledInfo res,
17019            int installReason) {
17020        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17021
17022        final PackageParser.Package oldPackage;
17023        final PackageSetting ps;
17024        final String pkgName = pkg.packageName;
17025        final int[] allUsers;
17026        final int[] installedUsers;
17027
17028        synchronized(mPackages) {
17029            oldPackage = mPackages.get(pkgName);
17030            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
17031
17032            // don't allow upgrade to target a release SDK from a pre-release SDK
17033            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
17034                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17035            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
17036                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17037            if (oldTargetsPreRelease
17038                    && !newTargetsPreRelease
17039                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
17040                Slog.w(TAG, "Can't install package targeting released sdk");
17041                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
17042                return;
17043            }
17044
17045            ps = mSettings.mPackages.get(pkgName);
17046
17047            // verify signatures are valid
17048            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
17049                if (!checkUpgradeKeySetLP(ps, pkg)) {
17050                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17051                            "New package not signed by keys specified by upgrade-keysets: "
17052                                    + pkgName);
17053                    return;
17054                }
17055            } else {
17056                // default to original signature matching
17057                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
17058                        != PackageManager.SIGNATURE_MATCH) {
17059                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17060                            "New package has a different signature: " + pkgName);
17061                    return;
17062                }
17063            }
17064
17065            // don't allow a system upgrade unless the upgrade hash matches
17066            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
17067                byte[] digestBytes = null;
17068                try {
17069                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
17070                    updateDigest(digest, new File(pkg.baseCodePath));
17071                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
17072                        for (String path : pkg.splitCodePaths) {
17073                            updateDigest(digest, new File(path));
17074                        }
17075                    }
17076                    digestBytes = digest.digest();
17077                } catch (NoSuchAlgorithmException | IOException e) {
17078                    res.setError(INSTALL_FAILED_INVALID_APK,
17079                            "Could not compute hash: " + pkgName);
17080                    return;
17081                }
17082                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
17083                    res.setError(INSTALL_FAILED_INVALID_APK,
17084                            "New package fails restrict-update check: " + pkgName);
17085                    return;
17086                }
17087                // retain upgrade restriction
17088                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
17089            }
17090
17091            // Check for shared user id changes
17092            String invalidPackageName =
17093                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
17094            if (invalidPackageName != null) {
17095                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
17096                        "Package " + invalidPackageName + " tried to change user "
17097                                + oldPackage.mSharedUserId);
17098                return;
17099            }
17100
17101            // In case of rollback, remember per-user/profile install state
17102            allUsers = sUserManager.getUserIds();
17103            installedUsers = ps.queryInstalledUsers(allUsers, true);
17104
17105            // don't allow an upgrade from full to ephemeral
17106            if (isInstantApp) {
17107                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
17108                    for (int currentUser : allUsers) {
17109                        if (!ps.getInstantApp(currentUser)) {
17110                            // can't downgrade from full to instant
17111                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17112                                    + " for user: " + currentUser);
17113                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17114                            return;
17115                        }
17116                    }
17117                } else if (!ps.getInstantApp(user.getIdentifier())) {
17118                    // can't downgrade from full to instant
17119                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17120                            + " for user: " + user.getIdentifier());
17121                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17122                    return;
17123                }
17124            }
17125        }
17126
17127        // Update what is removed
17128        res.removedInfo = new PackageRemovedInfo(this);
17129        res.removedInfo.uid = oldPackage.applicationInfo.uid;
17130        res.removedInfo.removedPackage = oldPackage.packageName;
17131        res.removedInfo.installerPackageName = ps.installerPackageName;
17132        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
17133        res.removedInfo.isUpdate = true;
17134        res.removedInfo.origUsers = installedUsers;
17135        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
17136        for (int i = 0; i < installedUsers.length; i++) {
17137            final int userId = installedUsers[i];
17138            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
17139        }
17140
17141        final int childCount = (oldPackage.childPackages != null)
17142                ? oldPackage.childPackages.size() : 0;
17143        for (int i = 0; i < childCount; i++) {
17144            boolean childPackageUpdated = false;
17145            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
17146            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17147            if (res.addedChildPackages != null) {
17148                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17149                if (childRes != null) {
17150                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
17151                    childRes.removedInfo.removedPackage = childPkg.packageName;
17152                    if (childPs != null) {
17153                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17154                    }
17155                    childRes.removedInfo.isUpdate = true;
17156                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
17157                    childPackageUpdated = true;
17158                }
17159            }
17160            if (!childPackageUpdated) {
17161                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
17162                childRemovedRes.removedPackage = childPkg.packageName;
17163                if (childPs != null) {
17164                    childRemovedRes.installerPackageName = childPs.installerPackageName;
17165                }
17166                childRemovedRes.isUpdate = false;
17167                childRemovedRes.dataRemoved = true;
17168                synchronized (mPackages) {
17169                    if (childPs != null) {
17170                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
17171                    }
17172                }
17173                if (res.removedInfo.removedChildPackages == null) {
17174                    res.removedInfo.removedChildPackages = new ArrayMap<>();
17175                }
17176                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
17177            }
17178        }
17179
17180        boolean sysPkg = (isSystemApp(oldPackage));
17181        if (sysPkg) {
17182            // Set the system/privileged flags as needed
17183            final boolean privileged =
17184                    (oldPackage.applicationInfo.privateFlags
17185                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17186            final int systemPolicyFlags = policyFlags
17187                    | PackageParser.PARSE_IS_SYSTEM
17188                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
17189
17190            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
17191                    user, allUsers, installerPackageName, res, installReason);
17192        } else {
17193            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
17194                    user, allUsers, installerPackageName, res, installReason);
17195        }
17196    }
17197
17198    @Override
17199    public List<String> getPreviousCodePaths(String packageName) {
17200        final int callingUid = Binder.getCallingUid();
17201        final List<String> result = new ArrayList<>();
17202        if (getInstantAppPackageName(callingUid) != null) {
17203            return result;
17204        }
17205        final PackageSetting ps = mSettings.mPackages.get(packageName);
17206        if (ps != null
17207                && ps.oldCodePaths != null
17208                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
17209            result.addAll(ps.oldCodePaths);
17210        }
17211        return result;
17212    }
17213
17214    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
17215            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17216            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17217            int installReason) {
17218        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
17219                + deletedPackage);
17220
17221        String pkgName = deletedPackage.packageName;
17222        boolean deletedPkg = true;
17223        boolean addedPkg = false;
17224        boolean updatedSettings = false;
17225        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
17226        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
17227                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
17228
17229        final long origUpdateTime = (pkg.mExtras != null)
17230                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
17231
17232        // First delete the existing package while retaining the data directory
17233        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17234                res.removedInfo, true, pkg)) {
17235            // If the existing package wasn't successfully deleted
17236            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
17237            deletedPkg = false;
17238        } else {
17239            // Successfully deleted the old package; proceed with replace.
17240
17241            // If deleted package lived in a container, give users a chance to
17242            // relinquish resources before killing.
17243            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
17244                if (DEBUG_INSTALL) {
17245                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
17246                }
17247                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
17248                final ArrayList<String> pkgList = new ArrayList<String>(1);
17249                pkgList.add(deletedPackage.applicationInfo.packageName);
17250                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
17251            }
17252
17253            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17254                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17255            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17256
17257            try {
17258                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
17259                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
17260                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17261                        installReason);
17262
17263                // Update the in-memory copy of the previous code paths.
17264                PackageSetting ps = mSettings.mPackages.get(pkgName);
17265                if (!killApp) {
17266                    if (ps.oldCodePaths == null) {
17267                        ps.oldCodePaths = new ArraySet<>();
17268                    }
17269                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
17270                    if (deletedPackage.splitCodePaths != null) {
17271                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
17272                    }
17273                } else {
17274                    ps.oldCodePaths = null;
17275                }
17276                if (ps.childPackageNames != null) {
17277                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
17278                        final String childPkgName = ps.childPackageNames.get(i);
17279                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
17280                        childPs.oldCodePaths = ps.oldCodePaths;
17281                    }
17282                }
17283                // set instant app status, but, only if it's explicitly specified
17284                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17285                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
17286                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
17287                prepareAppDataAfterInstallLIF(newPackage);
17288                addedPkg = true;
17289                mDexManager.notifyPackageUpdated(newPackage.packageName,
17290                        newPackage.baseCodePath, newPackage.splitCodePaths);
17291            } catch (PackageManagerException e) {
17292                res.setError("Package couldn't be installed in " + pkg.codePath, e);
17293            }
17294        }
17295
17296        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17297            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
17298
17299            // Revert all internal state mutations and added folders for the failed install
17300            if (addedPkg) {
17301                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17302                        res.removedInfo, true, null);
17303            }
17304
17305            // Restore the old package
17306            if (deletedPkg) {
17307                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
17308                File restoreFile = new File(deletedPackage.codePath);
17309                // Parse old package
17310                boolean oldExternal = isExternal(deletedPackage);
17311                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
17312                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
17313                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
17314                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
17315                try {
17316                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
17317                            null);
17318                } catch (PackageManagerException e) {
17319                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
17320                            + e.getMessage());
17321                    return;
17322                }
17323
17324                synchronized (mPackages) {
17325                    // Ensure the installer package name up to date
17326                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17327
17328                    // Update permissions for restored package
17329                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17330
17331                    mSettings.writeLPr();
17332                }
17333
17334                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
17335            }
17336        } else {
17337            synchronized (mPackages) {
17338                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
17339                if (ps != null) {
17340                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
17341                    if (res.removedInfo.removedChildPackages != null) {
17342                        final int childCount = res.removedInfo.removedChildPackages.size();
17343                        // Iterate in reverse as we may modify the collection
17344                        for (int i = childCount - 1; i >= 0; i--) {
17345                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
17346                            if (res.addedChildPackages.containsKey(childPackageName)) {
17347                                res.removedInfo.removedChildPackages.removeAt(i);
17348                            } else {
17349                                PackageRemovedInfo childInfo = res.removedInfo
17350                                        .removedChildPackages.valueAt(i);
17351                                childInfo.removedForAllUsers = mPackages.get(
17352                                        childInfo.removedPackage) == null;
17353                            }
17354                        }
17355                    }
17356                }
17357            }
17358        }
17359    }
17360
17361    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
17362            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17363            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17364            int installReason) {
17365        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
17366                + ", old=" + deletedPackage);
17367
17368        final boolean disabledSystem;
17369
17370        // Remove existing system package
17371        removePackageLI(deletedPackage, true);
17372
17373        synchronized (mPackages) {
17374            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
17375        }
17376        if (!disabledSystem) {
17377            // We didn't need to disable the .apk as a current system package,
17378            // which means we are replacing another update that is already
17379            // installed.  We need to make sure to delete the older one's .apk.
17380            res.removedInfo.args = createInstallArgsForExisting(0,
17381                    deletedPackage.applicationInfo.getCodePath(),
17382                    deletedPackage.applicationInfo.getResourcePath(),
17383                    getAppDexInstructionSets(deletedPackage.applicationInfo));
17384        } else {
17385            res.removedInfo.args = null;
17386        }
17387
17388        // Successfully disabled the old package. Now proceed with re-installation
17389        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17390                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17391        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17392
17393        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17394        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
17395                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
17396
17397        PackageParser.Package newPackage = null;
17398        try {
17399            // Add the package to the internal data structures
17400            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
17401
17402            // Set the update and install times
17403            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
17404            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
17405                    System.currentTimeMillis());
17406
17407            // Update the package dynamic state if succeeded
17408            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17409                // Now that the install succeeded make sure we remove data
17410                // directories for any child package the update removed.
17411                final int deletedChildCount = (deletedPackage.childPackages != null)
17412                        ? deletedPackage.childPackages.size() : 0;
17413                final int newChildCount = (newPackage.childPackages != null)
17414                        ? newPackage.childPackages.size() : 0;
17415                for (int i = 0; i < deletedChildCount; i++) {
17416                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
17417                    boolean childPackageDeleted = true;
17418                    for (int j = 0; j < newChildCount; j++) {
17419                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
17420                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
17421                            childPackageDeleted = false;
17422                            break;
17423                        }
17424                    }
17425                    if (childPackageDeleted) {
17426                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
17427                                deletedChildPkg.packageName);
17428                        if (ps != null && res.removedInfo.removedChildPackages != null) {
17429                            PackageRemovedInfo removedChildRes = res.removedInfo
17430                                    .removedChildPackages.get(deletedChildPkg.packageName);
17431                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
17432                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
17433                        }
17434                    }
17435                }
17436
17437                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17438                        installReason);
17439                prepareAppDataAfterInstallLIF(newPackage);
17440
17441                mDexManager.notifyPackageUpdated(newPackage.packageName,
17442                            newPackage.baseCodePath, newPackage.splitCodePaths);
17443            }
17444        } catch (PackageManagerException e) {
17445            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
17446            res.setError("Package couldn't be installed in " + pkg.codePath, e);
17447        }
17448
17449        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17450            // Re installation failed. Restore old information
17451            // Remove new pkg information
17452            if (newPackage != null) {
17453                removeInstalledPackageLI(newPackage, true);
17454            }
17455            // Add back the old system package
17456            try {
17457                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
17458            } catch (PackageManagerException e) {
17459                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
17460            }
17461
17462            synchronized (mPackages) {
17463                if (disabledSystem) {
17464                    enableSystemPackageLPw(deletedPackage);
17465                }
17466
17467                // Ensure the installer package name up to date
17468                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17469
17470                // Update permissions for restored package
17471                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17472
17473                mSettings.writeLPr();
17474            }
17475
17476            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
17477                    + " after failed upgrade");
17478        }
17479    }
17480
17481    /**
17482     * Checks whether the parent or any of the child packages have a change shared
17483     * user. For a package to be a valid update the shred users of the parent and
17484     * the children should match. We may later support changing child shared users.
17485     * @param oldPkg The updated package.
17486     * @param newPkg The update package.
17487     * @return The shared user that change between the versions.
17488     */
17489    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
17490            PackageParser.Package newPkg) {
17491        // Check parent shared user
17492        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
17493            return newPkg.packageName;
17494        }
17495        // Check child shared users
17496        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
17497        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
17498        for (int i = 0; i < newChildCount; i++) {
17499            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
17500            // If this child was present, did it have the same shared user?
17501            for (int j = 0; j < oldChildCount; j++) {
17502                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
17503                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
17504                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
17505                    return newChildPkg.packageName;
17506                }
17507            }
17508        }
17509        return null;
17510    }
17511
17512    private void removeNativeBinariesLI(PackageSetting ps) {
17513        // Remove the lib path for the parent package
17514        if (ps != null) {
17515            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
17516            // Remove the lib path for the child packages
17517            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
17518            for (int i = 0; i < childCount; i++) {
17519                PackageSetting childPs = null;
17520                synchronized (mPackages) {
17521                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
17522                }
17523                if (childPs != null) {
17524                    NativeLibraryHelper.removeNativeBinariesLI(childPs
17525                            .legacyNativeLibraryPathString);
17526                }
17527            }
17528        }
17529    }
17530
17531    private void enableSystemPackageLPw(PackageParser.Package pkg) {
17532        // Enable the parent package
17533        mSettings.enableSystemPackageLPw(pkg.packageName);
17534        // Enable the child packages
17535        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17536        for (int i = 0; i < childCount; i++) {
17537            PackageParser.Package childPkg = pkg.childPackages.get(i);
17538            mSettings.enableSystemPackageLPw(childPkg.packageName);
17539        }
17540    }
17541
17542    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
17543            PackageParser.Package newPkg) {
17544        // Disable the parent package (parent always replaced)
17545        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
17546        // Disable the child packages
17547        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
17548        for (int i = 0; i < childCount; i++) {
17549            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
17550            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
17551            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
17552        }
17553        return disabled;
17554    }
17555
17556    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
17557            String installerPackageName) {
17558        // Enable the parent package
17559        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
17560        // Enable the child packages
17561        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17562        for (int i = 0; i < childCount; i++) {
17563            PackageParser.Package childPkg = pkg.childPackages.get(i);
17564            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
17565        }
17566    }
17567
17568    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
17569        // Collect all used permissions in the UID
17570        ArraySet<String> usedPermissions = new ArraySet<>();
17571        final int packageCount = su.packages.size();
17572        for (int i = 0; i < packageCount; i++) {
17573            PackageSetting ps = su.packages.valueAt(i);
17574            if (ps.pkg == null) {
17575                continue;
17576            }
17577            final int requestedPermCount = ps.pkg.requestedPermissions.size();
17578            for (int j = 0; j < requestedPermCount; j++) {
17579                String permission = ps.pkg.requestedPermissions.get(j);
17580                BasePermission bp = mSettings.mPermissions.get(permission);
17581                if (bp != null) {
17582                    usedPermissions.add(permission);
17583                }
17584            }
17585        }
17586
17587        PermissionsState permissionsState = su.getPermissionsState();
17588        // Prune install permissions
17589        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
17590        final int installPermCount = installPermStates.size();
17591        for (int i = installPermCount - 1; i >= 0;  i--) {
17592            PermissionState permissionState = installPermStates.get(i);
17593            if (!usedPermissions.contains(permissionState.getName())) {
17594                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
17595                if (bp != null) {
17596                    permissionsState.revokeInstallPermission(bp);
17597                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
17598                            PackageManager.MASK_PERMISSION_FLAGS, 0);
17599                }
17600            }
17601        }
17602
17603        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
17604
17605        // Prune runtime permissions
17606        for (int userId : allUserIds) {
17607            List<PermissionState> runtimePermStates = permissionsState
17608                    .getRuntimePermissionStates(userId);
17609            final int runtimePermCount = runtimePermStates.size();
17610            for (int i = runtimePermCount - 1; i >= 0; i--) {
17611                PermissionState permissionState = runtimePermStates.get(i);
17612                if (!usedPermissions.contains(permissionState.getName())) {
17613                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
17614                    if (bp != null) {
17615                        permissionsState.revokeRuntimePermission(bp, userId);
17616                        permissionsState.updatePermissionFlags(bp, userId,
17617                                PackageManager.MASK_PERMISSION_FLAGS, 0);
17618                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
17619                                runtimePermissionChangedUserIds, userId);
17620                    }
17621                }
17622            }
17623        }
17624
17625        return runtimePermissionChangedUserIds;
17626    }
17627
17628    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
17629            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
17630        // Update the parent package setting
17631        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
17632                res, user, installReason);
17633        // Update the child packages setting
17634        final int childCount = (newPackage.childPackages != null)
17635                ? newPackage.childPackages.size() : 0;
17636        for (int i = 0; i < childCount; i++) {
17637            PackageParser.Package childPackage = newPackage.childPackages.get(i);
17638            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
17639            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
17640                    childRes.origUsers, childRes, user, installReason);
17641        }
17642    }
17643
17644    private void updateSettingsInternalLI(PackageParser.Package newPackage,
17645            String installerPackageName, int[] allUsers, int[] installedForUsers,
17646            PackageInstalledInfo res, UserHandle user, int installReason) {
17647        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
17648
17649        String pkgName = newPackage.packageName;
17650        synchronized (mPackages) {
17651            //write settings. the installStatus will be incomplete at this stage.
17652            //note that the new package setting would have already been
17653            //added to mPackages. It hasn't been persisted yet.
17654            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
17655            // TODO: Remove this write? It's also written at the end of this method
17656            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
17657            mSettings.writeLPr();
17658            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17659        }
17660
17661        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
17662        synchronized (mPackages) {
17663            updatePermissionsLPw(newPackage.packageName, newPackage,
17664                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
17665                            ? UPDATE_PERMISSIONS_ALL : 0));
17666            // For system-bundled packages, we assume that installing an upgraded version
17667            // of the package implies that the user actually wants to run that new code,
17668            // so we enable the package.
17669            PackageSetting ps = mSettings.mPackages.get(pkgName);
17670            final int userId = user.getIdentifier();
17671            if (ps != null) {
17672                if (isSystemApp(newPackage)) {
17673                    if (DEBUG_INSTALL) {
17674                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
17675                    }
17676                    // Enable system package for requested users
17677                    if (res.origUsers != null) {
17678                        for (int origUserId : res.origUsers) {
17679                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
17680                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
17681                                        origUserId, installerPackageName);
17682                            }
17683                        }
17684                    }
17685                    // Also convey the prior install/uninstall state
17686                    if (allUsers != null && installedForUsers != null) {
17687                        for (int currentUserId : allUsers) {
17688                            final boolean installed = ArrayUtils.contains(
17689                                    installedForUsers, currentUserId);
17690                            if (DEBUG_INSTALL) {
17691                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
17692                            }
17693                            ps.setInstalled(installed, currentUserId);
17694                        }
17695                        // these install state changes will be persisted in the
17696                        // upcoming call to mSettings.writeLPr().
17697                    }
17698                }
17699                // It's implied that when a user requests installation, they want the app to be
17700                // installed and enabled.
17701                if (userId != UserHandle.USER_ALL) {
17702                    ps.setInstalled(true, userId);
17703                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
17704                }
17705
17706                // When replacing an existing package, preserve the original install reason for all
17707                // users that had the package installed before.
17708                final Set<Integer> previousUserIds = new ArraySet<>();
17709                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
17710                    final int installReasonCount = res.removedInfo.installReasons.size();
17711                    for (int i = 0; i < installReasonCount; i++) {
17712                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
17713                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
17714                        ps.setInstallReason(previousInstallReason, previousUserId);
17715                        previousUserIds.add(previousUserId);
17716                    }
17717                }
17718
17719                // Set install reason for users that are having the package newly installed.
17720                if (userId == UserHandle.USER_ALL) {
17721                    for (int currentUserId : sUserManager.getUserIds()) {
17722                        if (!previousUserIds.contains(currentUserId)) {
17723                            ps.setInstallReason(installReason, currentUserId);
17724                        }
17725                    }
17726                } else if (!previousUserIds.contains(userId)) {
17727                    ps.setInstallReason(installReason, userId);
17728                }
17729                mSettings.writeKernelMappingLPr(ps);
17730            }
17731            res.name = pkgName;
17732            res.uid = newPackage.applicationInfo.uid;
17733            res.pkg = newPackage;
17734            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
17735            mSettings.setInstallerPackageName(pkgName, installerPackageName);
17736            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17737            //to update install status
17738            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
17739            mSettings.writeLPr();
17740            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17741        }
17742
17743        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17744    }
17745
17746    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
17747        try {
17748            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
17749            installPackageLI(args, res);
17750        } finally {
17751            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17752        }
17753    }
17754
17755    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
17756        final int installFlags = args.installFlags;
17757        final String installerPackageName = args.installerPackageName;
17758        final String volumeUuid = args.volumeUuid;
17759        final File tmpPackageFile = new File(args.getCodePath());
17760        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
17761        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
17762                || (args.volumeUuid != null));
17763        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
17764        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
17765        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
17766        boolean replace = false;
17767        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
17768        if (args.move != null) {
17769            // moving a complete application; perform an initial scan on the new install location
17770            scanFlags |= SCAN_INITIAL;
17771        }
17772        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
17773            scanFlags |= SCAN_DONT_KILL_APP;
17774        }
17775        if (instantApp) {
17776            scanFlags |= SCAN_AS_INSTANT_APP;
17777        }
17778        if (fullApp) {
17779            scanFlags |= SCAN_AS_FULL_APP;
17780        }
17781
17782        // Result object to be returned
17783        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17784
17785        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
17786
17787        // Sanity check
17788        if (instantApp && (forwardLocked || onExternal)) {
17789            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
17790                    + " external=" + onExternal);
17791            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17792            return;
17793        }
17794
17795        // Retrieve PackageSettings and parse package
17796        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
17797                | PackageParser.PARSE_ENFORCE_CODE
17798                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
17799                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
17800                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
17801                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
17802        PackageParser pp = new PackageParser();
17803        pp.setSeparateProcesses(mSeparateProcesses);
17804        pp.setDisplayMetrics(mMetrics);
17805        pp.setCallback(mPackageParserCallback);
17806
17807        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
17808        final PackageParser.Package pkg;
17809        try {
17810            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
17811        } catch (PackageParserException e) {
17812            res.setError("Failed parse during installPackageLI", e);
17813            return;
17814        } finally {
17815            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17816        }
17817
17818        // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
17819        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
17820            Slog.w(TAG, "Instant app package " + pkg.packageName + " does not target O");
17821            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17822                    "Instant app package must target O");
17823            return;
17824        }
17825        if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
17826            Slog.w(TAG, "Instant app package " + pkg.packageName
17827                    + " does not target targetSandboxVersion 2");
17828            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17829                    "Instant app package must use targetSanboxVersion 2");
17830            return;
17831        }
17832
17833        if (pkg.applicationInfo.isStaticSharedLibrary()) {
17834            // Static shared libraries have synthetic package names
17835            renameStaticSharedLibraryPackage(pkg);
17836
17837            // No static shared libs on external storage
17838            if (onExternal) {
17839                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
17840                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17841                        "Packages declaring static-shared libs cannot be updated");
17842                return;
17843            }
17844        }
17845
17846        // If we are installing a clustered package add results for the children
17847        if (pkg.childPackages != null) {
17848            synchronized (mPackages) {
17849                final int childCount = pkg.childPackages.size();
17850                for (int i = 0; i < childCount; i++) {
17851                    PackageParser.Package childPkg = pkg.childPackages.get(i);
17852                    PackageInstalledInfo childRes = new PackageInstalledInfo();
17853                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17854                    childRes.pkg = childPkg;
17855                    childRes.name = childPkg.packageName;
17856                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17857                    if (childPs != null) {
17858                        childRes.origUsers = childPs.queryInstalledUsers(
17859                                sUserManager.getUserIds(), true);
17860                    }
17861                    if ((mPackages.containsKey(childPkg.packageName))) {
17862                        childRes.removedInfo = new PackageRemovedInfo(this);
17863                        childRes.removedInfo.removedPackage = childPkg.packageName;
17864                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17865                    }
17866                    if (res.addedChildPackages == null) {
17867                        res.addedChildPackages = new ArrayMap<>();
17868                    }
17869                    res.addedChildPackages.put(childPkg.packageName, childRes);
17870                }
17871            }
17872        }
17873
17874        // If package doesn't declare API override, mark that we have an install
17875        // time CPU ABI override.
17876        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
17877            pkg.cpuAbiOverride = args.abiOverride;
17878        }
17879
17880        String pkgName = res.name = pkg.packageName;
17881        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
17882            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
17883                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
17884                return;
17885            }
17886        }
17887
17888        try {
17889            // either use what we've been given or parse directly from the APK
17890            if (args.certificates != null) {
17891                try {
17892                    PackageParser.populateCertificates(pkg, args.certificates);
17893                } catch (PackageParserException e) {
17894                    // there was something wrong with the certificates we were given;
17895                    // try to pull them from the APK
17896                    PackageParser.collectCertificates(pkg, parseFlags);
17897                }
17898            } else {
17899                PackageParser.collectCertificates(pkg, parseFlags);
17900            }
17901        } catch (PackageParserException e) {
17902            res.setError("Failed collect during installPackageLI", e);
17903            return;
17904        }
17905
17906        // Get rid of all references to package scan path via parser.
17907        pp = null;
17908        String oldCodePath = null;
17909        boolean systemApp = false;
17910        synchronized (mPackages) {
17911            // Check if installing already existing package
17912            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
17913                String oldName = mSettings.getRenamedPackageLPr(pkgName);
17914                if (pkg.mOriginalPackages != null
17915                        && pkg.mOriginalPackages.contains(oldName)
17916                        && mPackages.containsKey(oldName)) {
17917                    // This package is derived from an original package,
17918                    // and this device has been updating from that original
17919                    // name.  We must continue using the original name, so
17920                    // rename the new package here.
17921                    pkg.setPackageName(oldName);
17922                    pkgName = pkg.packageName;
17923                    replace = true;
17924                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
17925                            + oldName + " pkgName=" + pkgName);
17926                } else if (mPackages.containsKey(pkgName)) {
17927                    // This package, under its official name, already exists
17928                    // on the device; we should replace it.
17929                    replace = true;
17930                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
17931                }
17932
17933                // Child packages are installed through the parent package
17934                if (pkg.parentPackage != null) {
17935                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
17936                            "Package " + pkg.packageName + " is child of package "
17937                                    + pkg.parentPackage.parentPackage + ". Child packages "
17938                                    + "can be updated only through the parent package.");
17939                    return;
17940                }
17941
17942                if (replace) {
17943                    // Prevent apps opting out from runtime permissions
17944                    PackageParser.Package oldPackage = mPackages.get(pkgName);
17945                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
17946                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
17947                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
17948                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
17949                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
17950                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
17951                                        + " doesn't support runtime permissions but the old"
17952                                        + " target SDK " + oldTargetSdk + " does.");
17953                        return;
17954                    }
17955                    // Prevent apps from downgrading their targetSandbox.
17956                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
17957                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
17958                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
17959                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17960                                "Package " + pkg.packageName + " new target sandbox "
17961                                + newTargetSandbox + " is incompatible with the previous value of"
17962                                + oldTargetSandbox + ".");
17963                        return;
17964                    }
17965
17966                    // Prevent installing of child packages
17967                    if (oldPackage.parentPackage != null) {
17968                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
17969                                "Package " + pkg.packageName + " is child of package "
17970                                        + oldPackage.parentPackage + ". Child packages "
17971                                        + "can be updated only through the parent package.");
17972                        return;
17973                    }
17974                }
17975            }
17976
17977            PackageSetting ps = mSettings.mPackages.get(pkgName);
17978            if (ps != null) {
17979                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
17980
17981                // Static shared libs have same package with different versions where
17982                // we internally use a synthetic package name to allow multiple versions
17983                // of the same package, therefore we need to compare signatures against
17984                // the package setting for the latest library version.
17985                PackageSetting signatureCheckPs = ps;
17986                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17987                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
17988                    if (libraryEntry != null) {
17989                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
17990                    }
17991                }
17992
17993                // Quick sanity check that we're signed correctly if updating;
17994                // we'll check this again later when scanning, but we want to
17995                // bail early here before tripping over redefined permissions.
17996                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
17997                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
17998                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
17999                                + pkg.packageName + " upgrade keys do not match the "
18000                                + "previously installed version");
18001                        return;
18002                    }
18003                } else {
18004                    try {
18005                        verifySignaturesLP(signatureCheckPs, pkg);
18006                    } catch (PackageManagerException e) {
18007                        res.setError(e.error, e.getMessage());
18008                        return;
18009                    }
18010                }
18011
18012                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
18013                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
18014                    systemApp = (ps.pkg.applicationInfo.flags &
18015                            ApplicationInfo.FLAG_SYSTEM) != 0;
18016                }
18017                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18018            }
18019
18020            int N = pkg.permissions.size();
18021            for (int i = N-1; i >= 0; i--) {
18022                PackageParser.Permission perm = pkg.permissions.get(i);
18023                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
18024
18025                // Don't allow anyone but the system to define ephemeral permissions.
18026                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_EPHEMERAL) != 0
18027                        && !systemApp) {
18028                    Slog.w(TAG, "Non-System package " + pkg.packageName
18029                            + " attempting to delcare ephemeral permission "
18030                            + perm.info.name + "; Removing ephemeral.");
18031                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_EPHEMERAL;
18032                }
18033                // Check whether the newly-scanned package wants to define an already-defined perm
18034                if (bp != null) {
18035                    // If the defining package is signed with our cert, it's okay.  This
18036                    // also includes the "updating the same package" case, of course.
18037                    // "updating same package" could also involve key-rotation.
18038                    final boolean sigsOk;
18039                    if (bp.sourcePackage.equals(pkg.packageName)
18040                            && (bp.packageSetting instanceof PackageSetting)
18041                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
18042                                    scanFlags))) {
18043                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
18044                    } else {
18045                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
18046                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
18047                    }
18048                    if (!sigsOk) {
18049                        // If the owning package is the system itself, we log but allow
18050                        // install to proceed; we fail the install on all other permission
18051                        // redefinitions.
18052                        if (!bp.sourcePackage.equals("android")) {
18053                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
18054                                    + pkg.packageName + " attempting to redeclare permission "
18055                                    + perm.info.name + " already owned by " + bp.sourcePackage);
18056                            res.origPermission = perm.info.name;
18057                            res.origPackage = bp.sourcePackage;
18058                            return;
18059                        } else {
18060                            Slog.w(TAG, "Package " + pkg.packageName
18061                                    + " attempting to redeclare system permission "
18062                                    + perm.info.name + "; ignoring new declaration");
18063                            pkg.permissions.remove(i);
18064                        }
18065                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
18066                        // Prevent apps to change protection level to dangerous from any other
18067                        // type as this would allow a privilege escalation where an app adds a
18068                        // normal/signature permission in other app's group and later redefines
18069                        // it as dangerous leading to the group auto-grant.
18070                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
18071                                == PermissionInfo.PROTECTION_DANGEROUS) {
18072                            if (bp != null && !bp.isRuntime()) {
18073                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
18074                                        + "non-runtime permission " + perm.info.name
18075                                        + " to runtime; keeping old protection level");
18076                                perm.info.protectionLevel = bp.protectionLevel;
18077                            }
18078                        }
18079                    }
18080                }
18081            }
18082        }
18083
18084        if (systemApp) {
18085            if (onExternal) {
18086                // Abort update; system app can't be replaced with app on sdcard
18087                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
18088                        "Cannot install updates to system apps on sdcard");
18089                return;
18090            } else if (instantApp) {
18091                // Abort update; system app can't be replaced with an instant app
18092                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
18093                        "Cannot update a system app with an instant app");
18094                return;
18095            }
18096        }
18097
18098        if (args.move != null) {
18099            // We did an in-place move, so dex is ready to roll
18100            scanFlags |= SCAN_NO_DEX;
18101            scanFlags |= SCAN_MOVE;
18102
18103            synchronized (mPackages) {
18104                final PackageSetting ps = mSettings.mPackages.get(pkgName);
18105                if (ps == null) {
18106                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
18107                            "Missing settings for moved package " + pkgName);
18108                }
18109
18110                // We moved the entire application as-is, so bring over the
18111                // previously derived ABI information.
18112                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
18113                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
18114            }
18115
18116        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
18117            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
18118            scanFlags |= SCAN_NO_DEX;
18119
18120            try {
18121                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
18122                    args.abiOverride : pkg.cpuAbiOverride);
18123                final boolean extractNativeLibs = !pkg.isLibrary();
18124                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
18125                        extractNativeLibs, mAppLib32InstallDir);
18126            } catch (PackageManagerException pme) {
18127                Slog.e(TAG, "Error deriving application ABI", pme);
18128                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
18129                return;
18130            }
18131
18132            // Shared libraries for the package need to be updated.
18133            synchronized (mPackages) {
18134                try {
18135                    updateSharedLibrariesLPr(pkg, null);
18136                } catch (PackageManagerException e) {
18137                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18138                }
18139            }
18140
18141            // dexopt can take some time to complete, so, for instant apps, we skip this
18142            // step during installation. Instead, we'll take extra time the first time the
18143            // instant app starts. It's preferred to do it this way to provide continuous
18144            // progress to the user instead of mysteriously blocking somewhere in the
18145            // middle of running an instant app. The default behaviour can be overridden
18146            // via gservices.
18147            if (!instantApp || Global.getInt(
18148                        mContext.getContentResolver(), Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0) {
18149                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
18150                // Do not run PackageDexOptimizer through the local performDexOpt
18151                // method because `pkg` may not be in `mPackages` yet.
18152                //
18153                // Also, don't fail application installs if the dexopt step fails.
18154                mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
18155                        null /* instructionSets */, false /* checkProfiles */,
18156                        getCompilerFilterForReason(REASON_INSTALL),
18157                        getOrCreateCompilerPackageStats(pkg),
18158                        mDexManager.isUsedByOtherApps(pkg.packageName),
18159                        true /* bootComplete */);
18160                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18161            }
18162
18163            // Notify BackgroundDexOptService that the package has been changed.
18164            // If this is an update of a package which used to fail to compile,
18165            // BDOS will remove it from its blacklist.
18166            // TODO: Layering violation
18167            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
18168        }
18169
18170        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
18171            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
18172            return;
18173        }
18174
18175        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
18176
18177        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
18178                "installPackageLI")) {
18179            if (replace) {
18180                if (pkg.applicationInfo.isStaticSharedLibrary()) {
18181                    // Static libs have a synthetic package name containing the version
18182                    // and cannot be updated as an update would get a new package name,
18183                    // unless this is the exact same version code which is useful for
18184                    // development.
18185                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
18186                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
18187                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
18188                                + "static-shared libs cannot be updated");
18189                        return;
18190                    }
18191                }
18192                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
18193                        installerPackageName, res, args.installReason);
18194            } else {
18195                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
18196                        args.user, installerPackageName, volumeUuid, res, args.installReason);
18197            }
18198        }
18199
18200        synchronized (mPackages) {
18201            final PackageSetting ps = mSettings.mPackages.get(pkgName);
18202            if (ps != null) {
18203                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18204                ps.setUpdateAvailable(false /*updateAvailable*/);
18205            }
18206
18207            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18208            for (int i = 0; i < childCount; i++) {
18209                PackageParser.Package childPkg = pkg.childPackages.get(i);
18210                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
18211                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
18212                if (childPs != null) {
18213                    childRes.newUsers = childPs.queryInstalledUsers(
18214                            sUserManager.getUserIds(), true);
18215                }
18216            }
18217
18218            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
18219                updateSequenceNumberLP(ps, res.newUsers);
18220                updateInstantAppInstallerLocked(pkgName);
18221            }
18222        }
18223    }
18224
18225    private void startIntentFilterVerifications(int userId, boolean replacing,
18226            PackageParser.Package pkg) {
18227        if (mIntentFilterVerifierComponent == null) {
18228            Slog.w(TAG, "No IntentFilter verification will not be done as "
18229                    + "there is no IntentFilterVerifier available!");
18230            return;
18231        }
18232
18233        final int verifierUid = getPackageUid(
18234                mIntentFilterVerifierComponent.getPackageName(),
18235                MATCH_DEBUG_TRIAGED_MISSING,
18236                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
18237
18238        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18239        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
18240        mHandler.sendMessage(msg);
18241
18242        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18243        for (int i = 0; i < childCount; i++) {
18244            PackageParser.Package childPkg = pkg.childPackages.get(i);
18245            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18246            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
18247            mHandler.sendMessage(msg);
18248        }
18249    }
18250
18251    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
18252            PackageParser.Package pkg) {
18253        int size = pkg.activities.size();
18254        if (size == 0) {
18255            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18256                    "No activity, so no need to verify any IntentFilter!");
18257            return;
18258        }
18259
18260        final boolean hasDomainURLs = hasDomainURLs(pkg);
18261        if (!hasDomainURLs) {
18262            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18263                    "No domain URLs, so no need to verify any IntentFilter!");
18264            return;
18265        }
18266
18267        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
18268                + " if any IntentFilter from the " + size
18269                + " Activities needs verification ...");
18270
18271        int count = 0;
18272        final String packageName = pkg.packageName;
18273
18274        synchronized (mPackages) {
18275            // If this is a new install and we see that we've already run verification for this
18276            // package, we have nothing to do: it means the state was restored from backup.
18277            if (!replacing) {
18278                IntentFilterVerificationInfo ivi =
18279                        mSettings.getIntentFilterVerificationLPr(packageName);
18280                if (ivi != null) {
18281                    if (DEBUG_DOMAIN_VERIFICATION) {
18282                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
18283                                + ivi.getStatusString());
18284                    }
18285                    return;
18286                }
18287            }
18288
18289            // If any filters need to be verified, then all need to be.
18290            boolean needToVerify = false;
18291            for (PackageParser.Activity a : pkg.activities) {
18292                for (ActivityIntentInfo filter : a.intents) {
18293                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
18294                        if (DEBUG_DOMAIN_VERIFICATION) {
18295                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
18296                        }
18297                        needToVerify = true;
18298                        break;
18299                    }
18300                }
18301            }
18302
18303            if (needToVerify) {
18304                final int verificationId = mIntentFilterVerificationToken++;
18305                for (PackageParser.Activity a : pkg.activities) {
18306                    for (ActivityIntentInfo filter : a.intents) {
18307                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
18308                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18309                                    "Verification needed for IntentFilter:" + filter.toString());
18310                            mIntentFilterVerifier.addOneIntentFilterVerification(
18311                                    verifierUid, userId, verificationId, filter, packageName);
18312                            count++;
18313                        }
18314                    }
18315                }
18316            }
18317        }
18318
18319        if (count > 0) {
18320            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
18321                    + " IntentFilter verification" + (count > 1 ? "s" : "")
18322                    +  " for userId:" + userId);
18323            mIntentFilterVerifier.startVerifications(userId);
18324        } else {
18325            if (DEBUG_DOMAIN_VERIFICATION) {
18326                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
18327            }
18328        }
18329    }
18330
18331    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
18332        final ComponentName cn  = filter.activity.getComponentName();
18333        final String packageName = cn.getPackageName();
18334
18335        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
18336                packageName);
18337        if (ivi == null) {
18338            return true;
18339        }
18340        int status = ivi.getStatus();
18341        switch (status) {
18342            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
18343            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
18344                return true;
18345
18346            default:
18347                // Nothing to do
18348                return false;
18349        }
18350    }
18351
18352    private static boolean isMultiArch(ApplicationInfo info) {
18353        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
18354    }
18355
18356    private static boolean isExternal(PackageParser.Package pkg) {
18357        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18358    }
18359
18360    private static boolean isExternal(PackageSetting ps) {
18361        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18362    }
18363
18364    private static boolean isSystemApp(PackageParser.Package pkg) {
18365        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
18366    }
18367
18368    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
18369        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
18370    }
18371
18372    private static boolean hasDomainURLs(PackageParser.Package pkg) {
18373        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
18374    }
18375
18376    private static boolean isSystemApp(PackageSetting ps) {
18377        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
18378    }
18379
18380    private static boolean isUpdatedSystemApp(PackageSetting ps) {
18381        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
18382    }
18383
18384    private int packageFlagsToInstallFlags(PackageSetting ps) {
18385        int installFlags = 0;
18386        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
18387            // This existing package was an external ASEC install when we have
18388            // the external flag without a UUID
18389            installFlags |= PackageManager.INSTALL_EXTERNAL;
18390        }
18391        if (ps.isForwardLocked()) {
18392            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
18393        }
18394        return installFlags;
18395    }
18396
18397    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
18398        if (isExternal(pkg)) {
18399            if (TextUtils.isEmpty(pkg.volumeUuid)) {
18400                return StorageManager.UUID_PRIMARY_PHYSICAL;
18401            } else {
18402                return pkg.volumeUuid;
18403            }
18404        } else {
18405            return StorageManager.UUID_PRIVATE_INTERNAL;
18406        }
18407    }
18408
18409    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
18410        if (isExternal(pkg)) {
18411            if (TextUtils.isEmpty(pkg.volumeUuid)) {
18412                return mSettings.getExternalVersion();
18413            } else {
18414                return mSettings.findOrCreateVersion(pkg.volumeUuid);
18415            }
18416        } else {
18417            return mSettings.getInternalVersion();
18418        }
18419    }
18420
18421    private void deleteTempPackageFiles() {
18422        final FilenameFilter filter = new FilenameFilter() {
18423            public boolean accept(File dir, String name) {
18424                return name.startsWith("vmdl") && name.endsWith(".tmp");
18425            }
18426        };
18427        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
18428            file.delete();
18429        }
18430    }
18431
18432    @Override
18433    public void deletePackageAsUser(String packageName, int versionCode,
18434            IPackageDeleteObserver observer, int userId, int flags) {
18435        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
18436                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
18437    }
18438
18439    @Override
18440    public void deletePackageVersioned(VersionedPackage versionedPackage,
18441            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
18442        final int callingUid = Binder.getCallingUid();
18443        mContext.enforceCallingOrSelfPermission(
18444                android.Manifest.permission.DELETE_PACKAGES, null);
18445        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
18446        Preconditions.checkNotNull(versionedPackage);
18447        Preconditions.checkNotNull(observer);
18448        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
18449                PackageManager.VERSION_CODE_HIGHEST,
18450                Integer.MAX_VALUE, "versionCode must be >= -1");
18451
18452        final String packageName = versionedPackage.getPackageName();
18453        final int versionCode = versionedPackage.getVersionCode();
18454        final String internalPackageName;
18455        synchronized (mPackages) {
18456            // Normalize package name to handle renamed packages and static libs
18457            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
18458                    versionedPackage.getVersionCode());
18459        }
18460
18461        final int uid = Binder.getCallingUid();
18462        if (!isOrphaned(internalPackageName)
18463                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
18464            try {
18465                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
18466                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
18467                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
18468                observer.onUserActionRequired(intent);
18469            } catch (RemoteException re) {
18470            }
18471            return;
18472        }
18473        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
18474        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
18475        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
18476            mContext.enforceCallingOrSelfPermission(
18477                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
18478                    "deletePackage for user " + userId);
18479        }
18480
18481        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
18482            try {
18483                observer.onPackageDeleted(packageName,
18484                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
18485            } catch (RemoteException re) {
18486            }
18487            return;
18488        }
18489
18490        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
18491            try {
18492                observer.onPackageDeleted(packageName,
18493                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
18494            } catch (RemoteException re) {
18495            }
18496            return;
18497        }
18498
18499        if (DEBUG_REMOVE) {
18500            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
18501                    + " deleteAllUsers: " + deleteAllUsers + " version="
18502                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
18503                    ? "VERSION_CODE_HIGHEST" : versionCode));
18504        }
18505        // Queue up an async operation since the package deletion may take a little while.
18506        mHandler.post(new Runnable() {
18507            public void run() {
18508                mHandler.removeCallbacks(this);
18509                int returnCode;
18510                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
18511                boolean doDeletePackage = true;
18512                if (ps != null) {
18513                    final boolean targetIsInstantApp =
18514                            ps.getInstantApp(UserHandle.getUserId(callingUid));
18515                    doDeletePackage = !targetIsInstantApp
18516                            || canViewInstantApps;
18517                }
18518                if (doDeletePackage) {
18519                    if (!deleteAllUsers) {
18520                        returnCode = deletePackageX(internalPackageName, versionCode,
18521                                userId, deleteFlags);
18522                    } else {
18523                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
18524                                internalPackageName, users);
18525                        // If nobody is blocking uninstall, proceed with delete for all users
18526                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
18527                            returnCode = deletePackageX(internalPackageName, versionCode,
18528                                    userId, deleteFlags);
18529                        } else {
18530                            // Otherwise uninstall individually for users with blockUninstalls=false
18531                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
18532                            for (int userId : users) {
18533                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
18534                                    returnCode = deletePackageX(internalPackageName, versionCode,
18535                                            userId, userFlags);
18536                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
18537                                        Slog.w(TAG, "Package delete failed for user " + userId
18538                                                + ", returnCode " + returnCode);
18539                                    }
18540                                }
18541                            }
18542                            // The app has only been marked uninstalled for certain users.
18543                            // We still need to report that delete was blocked
18544                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
18545                        }
18546                    }
18547                } else {
18548                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18549                }
18550                try {
18551                    observer.onPackageDeleted(packageName, returnCode, null);
18552                } catch (RemoteException e) {
18553                    Log.i(TAG, "Observer no longer exists.");
18554                } //end catch
18555            } //end run
18556        });
18557    }
18558
18559    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
18560        if (pkg.staticSharedLibName != null) {
18561            return pkg.manifestPackageName;
18562        }
18563        return pkg.packageName;
18564    }
18565
18566    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
18567        // Handle renamed packages
18568        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
18569        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
18570
18571        // Is this a static library?
18572        SparseArray<SharedLibraryEntry> versionedLib =
18573                mStaticLibsByDeclaringPackage.get(packageName);
18574        if (versionedLib == null || versionedLib.size() <= 0) {
18575            return packageName;
18576        }
18577
18578        // Figure out which lib versions the caller can see
18579        SparseIntArray versionsCallerCanSee = null;
18580        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
18581        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
18582                && callingAppId != Process.ROOT_UID) {
18583            versionsCallerCanSee = new SparseIntArray();
18584            String libName = versionedLib.valueAt(0).info.getName();
18585            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
18586            if (uidPackages != null) {
18587                for (String uidPackage : uidPackages) {
18588                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
18589                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
18590                    if (libIdx >= 0) {
18591                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
18592                        versionsCallerCanSee.append(libVersion, libVersion);
18593                    }
18594                }
18595            }
18596        }
18597
18598        // Caller can see nothing - done
18599        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
18600            return packageName;
18601        }
18602
18603        // Find the version the caller can see and the app version code
18604        SharedLibraryEntry highestVersion = null;
18605        final int versionCount = versionedLib.size();
18606        for (int i = 0; i < versionCount; i++) {
18607            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
18608            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
18609                    libEntry.info.getVersion()) < 0) {
18610                continue;
18611            }
18612            final int libVersionCode = libEntry.info.getDeclaringPackage().getVersionCode();
18613            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
18614                if (libVersionCode == versionCode) {
18615                    return libEntry.apk;
18616                }
18617            } else if (highestVersion == null) {
18618                highestVersion = libEntry;
18619            } else if (libVersionCode  > highestVersion.info
18620                    .getDeclaringPackage().getVersionCode()) {
18621                highestVersion = libEntry;
18622            }
18623        }
18624
18625        if (highestVersion != null) {
18626            return highestVersion.apk;
18627        }
18628
18629        return packageName;
18630    }
18631
18632    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
18633        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
18634              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
18635            return true;
18636        }
18637        final int callingUserId = UserHandle.getUserId(callingUid);
18638        // If the caller installed the pkgName, then allow it to silently uninstall.
18639        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
18640            return true;
18641        }
18642
18643        // Allow package verifier to silently uninstall.
18644        if (mRequiredVerifierPackage != null &&
18645                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
18646            return true;
18647        }
18648
18649        // Allow package uninstaller to silently uninstall.
18650        if (mRequiredUninstallerPackage != null &&
18651                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
18652            return true;
18653        }
18654
18655        // Allow storage manager to silently uninstall.
18656        if (mStorageManagerPackage != null &&
18657                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
18658            return true;
18659        }
18660
18661        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
18662        // uninstall for device owner provisioning.
18663        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
18664                == PERMISSION_GRANTED) {
18665            return true;
18666        }
18667
18668        return false;
18669    }
18670
18671    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
18672        int[] result = EMPTY_INT_ARRAY;
18673        for (int userId : userIds) {
18674            if (getBlockUninstallForUser(packageName, userId)) {
18675                result = ArrayUtils.appendInt(result, userId);
18676            }
18677        }
18678        return result;
18679    }
18680
18681    @Override
18682    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
18683        final int callingUid = Binder.getCallingUid();
18684        if (getInstantAppPackageName(callingUid) != null
18685                && !isCallerSameApp(packageName, callingUid)) {
18686            return false;
18687        }
18688        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
18689    }
18690
18691    private boolean isPackageDeviceAdmin(String packageName, int userId) {
18692        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
18693                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
18694        try {
18695            if (dpm != null) {
18696                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
18697                        /* callingUserOnly =*/ false);
18698                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
18699                        : deviceOwnerComponentName.getPackageName();
18700                // Does the package contains the device owner?
18701                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
18702                // this check is probably not needed, since DO should be registered as a device
18703                // admin on some user too. (Original bug for this: b/17657954)
18704                if (packageName.equals(deviceOwnerPackageName)) {
18705                    return true;
18706                }
18707                // Does it contain a device admin for any user?
18708                int[] users;
18709                if (userId == UserHandle.USER_ALL) {
18710                    users = sUserManager.getUserIds();
18711                } else {
18712                    users = new int[]{userId};
18713                }
18714                for (int i = 0; i < users.length; ++i) {
18715                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
18716                        return true;
18717                    }
18718                }
18719            }
18720        } catch (RemoteException e) {
18721        }
18722        return false;
18723    }
18724
18725    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
18726        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
18727    }
18728
18729    /**
18730     *  This method is an internal method that could be get invoked either
18731     *  to delete an installed package or to clean up a failed installation.
18732     *  After deleting an installed package, a broadcast is sent to notify any
18733     *  listeners that the package has been removed. For cleaning up a failed
18734     *  installation, the broadcast is not necessary since the package's
18735     *  installation wouldn't have sent the initial broadcast either
18736     *  The key steps in deleting a package are
18737     *  deleting the package information in internal structures like mPackages,
18738     *  deleting the packages base directories through installd
18739     *  updating mSettings to reflect current status
18740     *  persisting settings for later use
18741     *  sending a broadcast if necessary
18742     */
18743    int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
18744        final PackageRemovedInfo info = new PackageRemovedInfo(this);
18745        final boolean res;
18746
18747        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
18748                ? UserHandle.USER_ALL : userId;
18749
18750        if (isPackageDeviceAdmin(packageName, removeUser)) {
18751            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
18752            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
18753        }
18754
18755        PackageSetting uninstalledPs = null;
18756        PackageParser.Package pkg = null;
18757
18758        // for the uninstall-updates case and restricted profiles, remember the per-
18759        // user handle installed state
18760        int[] allUsers;
18761        synchronized (mPackages) {
18762            uninstalledPs = mSettings.mPackages.get(packageName);
18763            if (uninstalledPs == null) {
18764                Slog.w(TAG, "Not removing non-existent package " + packageName);
18765                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18766            }
18767
18768            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
18769                    && uninstalledPs.versionCode != versionCode) {
18770                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
18771                        + uninstalledPs.versionCode + " != " + versionCode);
18772                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18773            }
18774
18775            // Static shared libs can be declared by any package, so let us not
18776            // allow removing a package if it provides a lib others depend on.
18777            pkg = mPackages.get(packageName);
18778
18779            allUsers = sUserManager.getUserIds();
18780
18781            if (pkg != null && pkg.staticSharedLibName != null) {
18782                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
18783                        pkg.staticSharedLibVersion);
18784                if (libEntry != null) {
18785                    for (int currUserId : allUsers) {
18786                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
18787                            continue;
18788                        }
18789                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
18790                                libEntry.info, 0, currUserId);
18791                        if (!ArrayUtils.isEmpty(libClientPackages)) {
18792                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
18793                                    + " hosting lib " + libEntry.info.getName() + " version "
18794                                    + libEntry.info.getVersion() + " used by " + libClientPackages
18795                                    + " for user " + currUserId);
18796                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
18797                        }
18798                    }
18799                }
18800            }
18801
18802            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
18803        }
18804
18805        final int freezeUser;
18806        if (isUpdatedSystemApp(uninstalledPs)
18807                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
18808            // We're downgrading a system app, which will apply to all users, so
18809            // freeze them all during the downgrade
18810            freezeUser = UserHandle.USER_ALL;
18811        } else {
18812            freezeUser = removeUser;
18813        }
18814
18815        synchronized (mInstallLock) {
18816            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
18817            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
18818                    deleteFlags, "deletePackageX")) {
18819                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
18820                        deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
18821            }
18822            synchronized (mPackages) {
18823                if (res) {
18824                    if (pkg != null) {
18825                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
18826                    }
18827                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
18828                    updateInstantAppInstallerLocked(packageName);
18829                }
18830            }
18831        }
18832
18833        if (res) {
18834            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
18835            info.sendPackageRemovedBroadcasts(killApp);
18836            info.sendSystemPackageUpdatedBroadcasts();
18837            info.sendSystemPackageAppearedBroadcasts();
18838        }
18839        // Force a gc here.
18840        Runtime.getRuntime().gc();
18841        // Delete the resources here after sending the broadcast to let
18842        // other processes clean up before deleting resources.
18843        if (info.args != null) {
18844            synchronized (mInstallLock) {
18845                info.args.doPostDeleteLI(true);
18846            }
18847        }
18848
18849        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18850    }
18851
18852    static class PackageRemovedInfo {
18853        final PackageSender packageSender;
18854        String removedPackage;
18855        String installerPackageName;
18856        int uid = -1;
18857        int removedAppId = -1;
18858        int[] origUsers;
18859        int[] removedUsers = null;
18860        int[] broadcastUsers = null;
18861        SparseArray<Integer> installReasons;
18862        boolean isRemovedPackageSystemUpdate = false;
18863        boolean isUpdate;
18864        boolean dataRemoved;
18865        boolean removedForAllUsers;
18866        boolean isStaticSharedLib;
18867        // Clean up resources deleted packages.
18868        InstallArgs args = null;
18869        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
18870        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
18871
18872        PackageRemovedInfo(PackageSender packageSender) {
18873            this.packageSender = packageSender;
18874        }
18875
18876        void sendPackageRemovedBroadcasts(boolean killApp) {
18877            sendPackageRemovedBroadcastInternal(killApp);
18878            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
18879            for (int i = 0; i < childCount; i++) {
18880                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18881                childInfo.sendPackageRemovedBroadcastInternal(killApp);
18882            }
18883        }
18884
18885        void sendSystemPackageUpdatedBroadcasts() {
18886            if (isRemovedPackageSystemUpdate) {
18887                sendSystemPackageUpdatedBroadcastsInternal();
18888                final int childCount = (removedChildPackages != null)
18889                        ? removedChildPackages.size() : 0;
18890                for (int i = 0; i < childCount; i++) {
18891                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18892                    if (childInfo.isRemovedPackageSystemUpdate) {
18893                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
18894                    }
18895                }
18896            }
18897        }
18898
18899        void sendSystemPackageAppearedBroadcasts() {
18900            final int packageCount = (appearedChildPackages != null)
18901                    ? appearedChildPackages.size() : 0;
18902            for (int i = 0; i < packageCount; i++) {
18903                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
18904                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
18905                    true, UserHandle.getAppId(installedInfo.uid),
18906                    installedInfo.newUsers);
18907            }
18908        }
18909
18910        private void sendSystemPackageUpdatedBroadcastsInternal() {
18911            Bundle extras = new Bundle(2);
18912            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
18913            extras.putBoolean(Intent.EXTRA_REPLACING, true);
18914            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18915                removedPackage, extras, 0, null /*targetPackage*/, null, null);
18916            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18917                removedPackage, extras, 0, null /*targetPackage*/, null, null);
18918            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
18919                null, null, 0, removedPackage, null, null);
18920            if (installerPackageName != null) {
18921                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18922                        removedPackage, extras, 0 /*flags*/,
18923                        installerPackageName, null, null);
18924                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18925                        removedPackage, extras, 0 /*flags*/,
18926                        installerPackageName, null, null);
18927            }
18928        }
18929
18930        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
18931            // Don't send static shared library removal broadcasts as these
18932            // libs are visible only the the apps that depend on them an one
18933            // cannot remove the library if it has a dependency.
18934            if (isStaticSharedLib) {
18935                return;
18936            }
18937            Bundle extras = new Bundle(2);
18938            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
18939            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
18940            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
18941            if (isUpdate || isRemovedPackageSystemUpdate) {
18942                extras.putBoolean(Intent.EXTRA_REPLACING, true);
18943            }
18944            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
18945            if (removedPackage != null) {
18946                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18947                    removedPackage, extras, 0, null /*targetPackage*/, null, broadcastUsers);
18948                if (installerPackageName != null) {
18949                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18950                            removedPackage, extras, 0 /*flags*/,
18951                            installerPackageName, null, broadcastUsers);
18952                }
18953                if (dataRemoved && !isRemovedPackageSystemUpdate) {
18954                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
18955                        removedPackage, extras,
18956                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18957                        null, null, broadcastUsers);
18958                }
18959            }
18960            if (removedAppId >= 0) {
18961                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras,
18962                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, null, null, broadcastUsers);
18963            }
18964        }
18965
18966        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
18967            removedUsers = userIds;
18968            if (removedUsers == null) {
18969                broadcastUsers = null;
18970                return;
18971            }
18972
18973            broadcastUsers = EMPTY_INT_ARRAY;
18974            for (int i = userIds.length - 1; i >= 0; --i) {
18975                final int userId = userIds[i];
18976                if (deletedPackageSetting.getInstantApp(userId)) {
18977                    continue;
18978                }
18979                broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
18980            }
18981        }
18982    }
18983
18984    /*
18985     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
18986     * flag is not set, the data directory is removed as well.
18987     * make sure this flag is set for partially installed apps. If not its meaningless to
18988     * delete a partially installed application.
18989     */
18990    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
18991            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
18992        String packageName = ps.name;
18993        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
18994        // Retrieve object to delete permissions for shared user later on
18995        final PackageParser.Package deletedPkg;
18996        final PackageSetting deletedPs;
18997        // reader
18998        synchronized (mPackages) {
18999            deletedPkg = mPackages.get(packageName);
19000            deletedPs = mSettings.mPackages.get(packageName);
19001            if (outInfo != null) {
19002                outInfo.removedPackage = packageName;
19003                outInfo.installerPackageName = ps.installerPackageName;
19004                outInfo.isStaticSharedLib = deletedPkg != null
19005                        && deletedPkg.staticSharedLibName != null;
19006                outInfo.populateUsers(deletedPs == null ? null
19007                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
19008            }
19009        }
19010
19011        removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
19012
19013        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
19014            final PackageParser.Package resolvedPkg;
19015            if (deletedPkg != null) {
19016                resolvedPkg = deletedPkg;
19017            } else {
19018                // We don't have a parsed package when it lives on an ejected
19019                // adopted storage device, so fake something together
19020                resolvedPkg = new PackageParser.Package(ps.name);
19021                resolvedPkg.setVolumeUuid(ps.volumeUuid);
19022            }
19023            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
19024                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19025            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
19026            if (outInfo != null) {
19027                outInfo.dataRemoved = true;
19028            }
19029            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
19030        }
19031
19032        int removedAppId = -1;
19033
19034        // writer
19035        synchronized (mPackages) {
19036            boolean installedStateChanged = false;
19037            if (deletedPs != null) {
19038                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
19039                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
19040                    clearDefaultBrowserIfNeeded(packageName);
19041                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
19042                    removedAppId = mSettings.removePackageLPw(packageName);
19043                    if (outInfo != null) {
19044                        outInfo.removedAppId = removedAppId;
19045                    }
19046                    updatePermissionsLPw(deletedPs.name, null, 0);
19047                    if (deletedPs.sharedUser != null) {
19048                        // Remove permissions associated with package. Since runtime
19049                        // permissions are per user we have to kill the removed package
19050                        // or packages running under the shared user of the removed
19051                        // package if revoking the permissions requested only by the removed
19052                        // package is successful and this causes a change in gids.
19053                        for (int userId : UserManagerService.getInstance().getUserIds()) {
19054                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
19055                                    userId);
19056                            if (userIdToKill == UserHandle.USER_ALL
19057                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
19058                                // If gids changed for this user, kill all affected packages.
19059                                mHandler.post(new Runnable() {
19060                                    @Override
19061                                    public void run() {
19062                                        // This has to happen with no lock held.
19063                                        killApplication(deletedPs.name, deletedPs.appId,
19064                                                KILL_APP_REASON_GIDS_CHANGED);
19065                                    }
19066                                });
19067                                break;
19068                            }
19069                        }
19070                    }
19071                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
19072                }
19073                // make sure to preserve per-user disabled state if this removal was just
19074                // a downgrade of a system app to the factory package
19075                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
19076                    if (DEBUG_REMOVE) {
19077                        Slog.d(TAG, "Propagating install state across downgrade");
19078                    }
19079                    for (int userId : allUserHandles) {
19080                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
19081                        if (DEBUG_REMOVE) {
19082                            Slog.d(TAG, "    user " + userId + " => " + installed);
19083                        }
19084                        if (installed != ps.getInstalled(userId)) {
19085                            installedStateChanged = true;
19086                        }
19087                        ps.setInstalled(installed, userId);
19088                    }
19089                }
19090            }
19091            // can downgrade to reader
19092            if (writeSettings) {
19093                // Save settings now
19094                mSettings.writeLPr();
19095            }
19096            if (installedStateChanged) {
19097                mSettings.writeKernelMappingLPr(ps);
19098            }
19099        }
19100        if (removedAppId != -1) {
19101            // A user ID was deleted here. Go through all users and remove it
19102            // from KeyStore.
19103            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
19104        }
19105    }
19106
19107    static boolean locationIsPrivileged(File path) {
19108        try {
19109            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
19110                    .getCanonicalPath();
19111            return path.getCanonicalPath().startsWith(privilegedAppDir);
19112        } catch (IOException e) {
19113            Slog.e(TAG, "Unable to access code path " + path);
19114        }
19115        return false;
19116    }
19117
19118    /*
19119     * Tries to delete system package.
19120     */
19121    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
19122            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
19123            boolean writeSettings) {
19124        if (deletedPs.parentPackageName != null) {
19125            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
19126            return false;
19127        }
19128
19129        final boolean applyUserRestrictions
19130                = (allUserHandles != null) && (outInfo.origUsers != null);
19131        final PackageSetting disabledPs;
19132        // Confirm if the system package has been updated
19133        // An updated system app can be deleted. This will also have to restore
19134        // the system pkg from system partition
19135        // reader
19136        synchronized (mPackages) {
19137            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
19138        }
19139
19140        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
19141                + " disabledPs=" + disabledPs);
19142
19143        if (disabledPs == null) {
19144            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
19145            return false;
19146        } else if (DEBUG_REMOVE) {
19147            Slog.d(TAG, "Deleting system pkg from data partition");
19148        }
19149
19150        if (DEBUG_REMOVE) {
19151            if (applyUserRestrictions) {
19152                Slog.d(TAG, "Remembering install states:");
19153                for (int userId : allUserHandles) {
19154                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
19155                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
19156                }
19157            }
19158        }
19159
19160        // Delete the updated package
19161        outInfo.isRemovedPackageSystemUpdate = true;
19162        if (outInfo.removedChildPackages != null) {
19163            final int childCount = (deletedPs.childPackageNames != null)
19164                    ? deletedPs.childPackageNames.size() : 0;
19165            for (int i = 0; i < childCount; i++) {
19166                String childPackageName = deletedPs.childPackageNames.get(i);
19167                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
19168                        .contains(childPackageName)) {
19169                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19170                            childPackageName);
19171                    if (childInfo != null) {
19172                        childInfo.isRemovedPackageSystemUpdate = true;
19173                    }
19174                }
19175            }
19176        }
19177
19178        if (disabledPs.versionCode < deletedPs.versionCode) {
19179            // Delete data for downgrades
19180            flags &= ~PackageManager.DELETE_KEEP_DATA;
19181        } else {
19182            // Preserve data by setting flag
19183            flags |= PackageManager.DELETE_KEEP_DATA;
19184        }
19185
19186        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
19187                outInfo, writeSettings, disabledPs.pkg);
19188        if (!ret) {
19189            return false;
19190        }
19191
19192        // writer
19193        synchronized (mPackages) {
19194            // Reinstate the old system package
19195            enableSystemPackageLPw(disabledPs.pkg);
19196            // Remove any native libraries from the upgraded package.
19197            removeNativeBinariesLI(deletedPs);
19198        }
19199
19200        // Install the system package
19201        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
19202        int parseFlags = mDefParseFlags
19203                | PackageParser.PARSE_MUST_BE_APK
19204                | PackageParser.PARSE_IS_SYSTEM
19205                | PackageParser.PARSE_IS_SYSTEM_DIR;
19206        if (locationIsPrivileged(disabledPs.codePath)) {
19207            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
19208        }
19209
19210        final PackageParser.Package newPkg;
19211        try {
19212            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */,
19213                0 /* currentTime */, null);
19214        } catch (PackageManagerException e) {
19215            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
19216                    + e.getMessage());
19217            return false;
19218        }
19219
19220        try {
19221            // update shared libraries for the newly re-installed system package
19222            updateSharedLibrariesLPr(newPkg, null);
19223        } catch (PackageManagerException e) {
19224            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
19225        }
19226
19227        prepareAppDataAfterInstallLIF(newPkg);
19228
19229        // writer
19230        synchronized (mPackages) {
19231            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
19232
19233            // Propagate the permissions state as we do not want to drop on the floor
19234            // runtime permissions. The update permissions method below will take
19235            // care of removing obsolete permissions and grant install permissions.
19236            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
19237            updatePermissionsLPw(newPkg.packageName, newPkg,
19238                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
19239
19240            if (applyUserRestrictions) {
19241                boolean installedStateChanged = false;
19242                if (DEBUG_REMOVE) {
19243                    Slog.d(TAG, "Propagating install state across reinstall");
19244                }
19245                for (int userId : allUserHandles) {
19246                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
19247                    if (DEBUG_REMOVE) {
19248                        Slog.d(TAG, "    user " + userId + " => " + installed);
19249                    }
19250                    if (installed != ps.getInstalled(userId)) {
19251                        installedStateChanged = true;
19252                    }
19253                    ps.setInstalled(installed, userId);
19254
19255                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19256                }
19257                // Regardless of writeSettings we need to ensure that this restriction
19258                // state propagation is persisted
19259                mSettings.writeAllUsersPackageRestrictionsLPr();
19260                if (installedStateChanged) {
19261                    mSettings.writeKernelMappingLPr(ps);
19262                }
19263            }
19264            // can downgrade to reader here
19265            if (writeSettings) {
19266                mSettings.writeLPr();
19267            }
19268        }
19269        return true;
19270    }
19271
19272    private boolean deleteInstalledPackageLIF(PackageSetting ps,
19273            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
19274            PackageRemovedInfo outInfo, boolean writeSettings,
19275            PackageParser.Package replacingPackage) {
19276        synchronized (mPackages) {
19277            if (outInfo != null) {
19278                outInfo.uid = ps.appId;
19279            }
19280
19281            if (outInfo != null && outInfo.removedChildPackages != null) {
19282                final int childCount = (ps.childPackageNames != null)
19283                        ? ps.childPackageNames.size() : 0;
19284                for (int i = 0; i < childCount; i++) {
19285                    String childPackageName = ps.childPackageNames.get(i);
19286                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
19287                    if (childPs == null) {
19288                        return false;
19289                    }
19290                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19291                            childPackageName);
19292                    if (childInfo != null) {
19293                        childInfo.uid = childPs.appId;
19294                    }
19295                }
19296            }
19297        }
19298
19299        // Delete package data from internal structures and also remove data if flag is set
19300        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
19301
19302        // Delete the child packages data
19303        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
19304        for (int i = 0; i < childCount; i++) {
19305            PackageSetting childPs;
19306            synchronized (mPackages) {
19307                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
19308            }
19309            if (childPs != null) {
19310                PackageRemovedInfo childOutInfo = (outInfo != null
19311                        && outInfo.removedChildPackages != null)
19312                        ? outInfo.removedChildPackages.get(childPs.name) : null;
19313                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
19314                        && (replacingPackage != null
19315                        && !replacingPackage.hasChildPackage(childPs.name))
19316                        ? flags & ~DELETE_KEEP_DATA : flags;
19317                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
19318                        deleteFlags, writeSettings);
19319            }
19320        }
19321
19322        // Delete application code and resources only for parent packages
19323        if (ps.parentPackageName == null) {
19324            if (deleteCodeAndResources && (outInfo != null)) {
19325                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
19326                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
19327                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
19328            }
19329        }
19330
19331        return true;
19332    }
19333
19334    @Override
19335    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
19336            int userId) {
19337        mContext.enforceCallingOrSelfPermission(
19338                android.Manifest.permission.DELETE_PACKAGES, null);
19339        synchronized (mPackages) {
19340            // Cannot block uninstall of static shared libs as they are
19341            // considered a part of the using app (emulating static linking).
19342            // Also static libs are installed always on internal storage.
19343            PackageParser.Package pkg = mPackages.get(packageName);
19344            if (pkg != null && pkg.staticSharedLibName != null) {
19345                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
19346                        + " providing static shared library: " + pkg.staticSharedLibName);
19347                return false;
19348            }
19349            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
19350            mSettings.writePackageRestrictionsLPr(userId);
19351        }
19352        return true;
19353    }
19354
19355    @Override
19356    public boolean getBlockUninstallForUser(String packageName, int userId) {
19357        synchronized (mPackages) {
19358            final PackageSetting ps = mSettings.mPackages.get(packageName);
19359            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
19360                return false;
19361            }
19362            return mSettings.getBlockUninstallLPr(userId, packageName);
19363        }
19364    }
19365
19366    @Override
19367    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
19368        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
19369        synchronized (mPackages) {
19370            PackageSetting ps = mSettings.mPackages.get(packageName);
19371            if (ps == null) {
19372                Log.w(TAG, "Package doesn't exist: " + packageName);
19373                return false;
19374            }
19375            if (systemUserApp) {
19376                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
19377            } else {
19378                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
19379            }
19380            mSettings.writeLPr();
19381        }
19382        return true;
19383    }
19384
19385    /*
19386     * This method handles package deletion in general
19387     */
19388    private boolean deletePackageLIF(String packageName, UserHandle user,
19389            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
19390            PackageRemovedInfo outInfo, boolean writeSettings,
19391            PackageParser.Package replacingPackage) {
19392        if (packageName == null) {
19393            Slog.w(TAG, "Attempt to delete null packageName.");
19394            return false;
19395        }
19396
19397        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
19398
19399        PackageSetting ps;
19400        synchronized (mPackages) {
19401            ps = mSettings.mPackages.get(packageName);
19402            if (ps == null) {
19403                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19404                return false;
19405            }
19406
19407            if (ps.parentPackageName != null && (!isSystemApp(ps)
19408                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
19409                if (DEBUG_REMOVE) {
19410                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
19411                            + ((user == null) ? UserHandle.USER_ALL : user));
19412                }
19413                final int removedUserId = (user != null) ? user.getIdentifier()
19414                        : UserHandle.USER_ALL;
19415                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
19416                    return false;
19417                }
19418                markPackageUninstalledForUserLPw(ps, user);
19419                scheduleWritePackageRestrictionsLocked(user);
19420                return true;
19421            }
19422        }
19423
19424        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
19425                && user.getIdentifier() != UserHandle.USER_ALL)) {
19426            // The caller is asking that the package only be deleted for a single
19427            // user.  To do this, we just mark its uninstalled state and delete
19428            // its data. If this is a system app, we only allow this to happen if
19429            // they have set the special DELETE_SYSTEM_APP which requests different
19430            // semantics than normal for uninstalling system apps.
19431            markPackageUninstalledForUserLPw(ps, user);
19432
19433            if (!isSystemApp(ps)) {
19434                // Do not uninstall the APK if an app should be cached
19435                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
19436                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
19437                    // Other user still have this package installed, so all
19438                    // we need to do is clear this user's data and save that
19439                    // it is uninstalled.
19440                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
19441                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
19442                        return false;
19443                    }
19444                    scheduleWritePackageRestrictionsLocked(user);
19445                    return true;
19446                } else {
19447                    // We need to set it back to 'installed' so the uninstall
19448                    // broadcasts will be sent correctly.
19449                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
19450                    ps.setInstalled(true, user.getIdentifier());
19451                    mSettings.writeKernelMappingLPr(ps);
19452                }
19453            } else {
19454                // This is a system app, so we assume that the
19455                // other users still have this package installed, so all
19456                // we need to do is clear this user's data and save that
19457                // it is uninstalled.
19458                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
19459                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
19460                    return false;
19461                }
19462                scheduleWritePackageRestrictionsLocked(user);
19463                return true;
19464            }
19465        }
19466
19467        // If we are deleting a composite package for all users, keep track
19468        // of result for each child.
19469        if (ps.childPackageNames != null && outInfo != null) {
19470            synchronized (mPackages) {
19471                final int childCount = ps.childPackageNames.size();
19472                outInfo.removedChildPackages = new ArrayMap<>(childCount);
19473                for (int i = 0; i < childCount; i++) {
19474                    String childPackageName = ps.childPackageNames.get(i);
19475                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
19476                    childInfo.removedPackage = childPackageName;
19477                    childInfo.installerPackageName = ps.installerPackageName;
19478                    outInfo.removedChildPackages.put(childPackageName, childInfo);
19479                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
19480                    if (childPs != null) {
19481                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
19482                    }
19483                }
19484            }
19485        }
19486
19487        boolean ret = false;
19488        if (isSystemApp(ps)) {
19489            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
19490            // When an updated system application is deleted we delete the existing resources
19491            // as well and fall back to existing code in system partition
19492            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
19493        } else {
19494            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
19495            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
19496                    outInfo, writeSettings, replacingPackage);
19497        }
19498
19499        // Take a note whether we deleted the package for all users
19500        if (outInfo != null) {
19501            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
19502            if (outInfo.removedChildPackages != null) {
19503                synchronized (mPackages) {
19504                    final int childCount = outInfo.removedChildPackages.size();
19505                    for (int i = 0; i < childCount; i++) {
19506                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
19507                        if (childInfo != null) {
19508                            childInfo.removedForAllUsers = mPackages.get(
19509                                    childInfo.removedPackage) == null;
19510                        }
19511                    }
19512                }
19513            }
19514            // If we uninstalled an update to a system app there may be some
19515            // child packages that appeared as they are declared in the system
19516            // app but were not declared in the update.
19517            if (isSystemApp(ps)) {
19518                synchronized (mPackages) {
19519                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
19520                    final int childCount = (updatedPs.childPackageNames != null)
19521                            ? updatedPs.childPackageNames.size() : 0;
19522                    for (int i = 0; i < childCount; i++) {
19523                        String childPackageName = updatedPs.childPackageNames.get(i);
19524                        if (outInfo.removedChildPackages == null
19525                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
19526                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
19527                            if (childPs == null) {
19528                                continue;
19529                            }
19530                            PackageInstalledInfo installRes = new PackageInstalledInfo();
19531                            installRes.name = childPackageName;
19532                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
19533                            installRes.pkg = mPackages.get(childPackageName);
19534                            installRes.uid = childPs.pkg.applicationInfo.uid;
19535                            if (outInfo.appearedChildPackages == null) {
19536                                outInfo.appearedChildPackages = new ArrayMap<>();
19537                            }
19538                            outInfo.appearedChildPackages.put(childPackageName, installRes);
19539                        }
19540                    }
19541                }
19542            }
19543        }
19544
19545        return ret;
19546    }
19547
19548    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
19549        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
19550                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
19551        for (int nextUserId : userIds) {
19552            if (DEBUG_REMOVE) {
19553                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
19554            }
19555            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
19556                    false /*installed*/,
19557                    true /*stopped*/,
19558                    true /*notLaunched*/,
19559                    false /*hidden*/,
19560                    false /*suspended*/,
19561                    false /*instantApp*/,
19562                    null /*lastDisableAppCaller*/,
19563                    null /*enabledComponents*/,
19564                    null /*disabledComponents*/,
19565                    ps.readUserState(nextUserId).domainVerificationStatus,
19566                    0, PackageManager.INSTALL_REASON_UNKNOWN);
19567        }
19568        mSettings.writeKernelMappingLPr(ps);
19569    }
19570
19571    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
19572            PackageRemovedInfo outInfo) {
19573        final PackageParser.Package pkg;
19574        synchronized (mPackages) {
19575            pkg = mPackages.get(ps.name);
19576        }
19577
19578        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
19579                : new int[] {userId};
19580        for (int nextUserId : userIds) {
19581            if (DEBUG_REMOVE) {
19582                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
19583                        + nextUserId);
19584            }
19585
19586            destroyAppDataLIF(pkg, userId,
19587                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19588            destroyAppProfilesLIF(pkg, userId);
19589            clearDefaultBrowserIfNeededForUser(ps.name, userId);
19590            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
19591            schedulePackageCleaning(ps.name, nextUserId, false);
19592            synchronized (mPackages) {
19593                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
19594                    scheduleWritePackageRestrictionsLocked(nextUserId);
19595                }
19596                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
19597            }
19598        }
19599
19600        if (outInfo != null) {
19601            outInfo.removedPackage = ps.name;
19602            outInfo.installerPackageName = ps.installerPackageName;
19603            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
19604            outInfo.removedAppId = ps.appId;
19605            outInfo.removedUsers = userIds;
19606            outInfo.broadcastUsers = userIds;
19607        }
19608
19609        return true;
19610    }
19611
19612    private final class ClearStorageConnection implements ServiceConnection {
19613        IMediaContainerService mContainerService;
19614
19615        @Override
19616        public void onServiceConnected(ComponentName name, IBinder service) {
19617            synchronized (this) {
19618                mContainerService = IMediaContainerService.Stub
19619                        .asInterface(Binder.allowBlocking(service));
19620                notifyAll();
19621            }
19622        }
19623
19624        @Override
19625        public void onServiceDisconnected(ComponentName name) {
19626        }
19627    }
19628
19629    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
19630        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
19631
19632        final boolean mounted;
19633        if (Environment.isExternalStorageEmulated()) {
19634            mounted = true;
19635        } else {
19636            final String status = Environment.getExternalStorageState();
19637
19638            mounted = status.equals(Environment.MEDIA_MOUNTED)
19639                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
19640        }
19641
19642        if (!mounted) {
19643            return;
19644        }
19645
19646        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
19647        int[] users;
19648        if (userId == UserHandle.USER_ALL) {
19649            users = sUserManager.getUserIds();
19650        } else {
19651            users = new int[] { userId };
19652        }
19653        final ClearStorageConnection conn = new ClearStorageConnection();
19654        if (mContext.bindServiceAsUser(
19655                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
19656            try {
19657                for (int curUser : users) {
19658                    long timeout = SystemClock.uptimeMillis() + 5000;
19659                    synchronized (conn) {
19660                        long now;
19661                        while (conn.mContainerService == null &&
19662                                (now = SystemClock.uptimeMillis()) < timeout) {
19663                            try {
19664                                conn.wait(timeout - now);
19665                            } catch (InterruptedException e) {
19666                            }
19667                        }
19668                    }
19669                    if (conn.mContainerService == null) {
19670                        return;
19671                    }
19672
19673                    final UserEnvironment userEnv = new UserEnvironment(curUser);
19674                    clearDirectory(conn.mContainerService,
19675                            userEnv.buildExternalStorageAppCacheDirs(packageName));
19676                    if (allData) {
19677                        clearDirectory(conn.mContainerService,
19678                                userEnv.buildExternalStorageAppDataDirs(packageName));
19679                        clearDirectory(conn.mContainerService,
19680                                userEnv.buildExternalStorageAppMediaDirs(packageName));
19681                    }
19682                }
19683            } finally {
19684                mContext.unbindService(conn);
19685            }
19686        }
19687    }
19688
19689    @Override
19690    public void clearApplicationProfileData(String packageName) {
19691        enforceSystemOrRoot("Only the system can clear all profile data");
19692
19693        final PackageParser.Package pkg;
19694        synchronized (mPackages) {
19695            pkg = mPackages.get(packageName);
19696        }
19697
19698        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
19699            synchronized (mInstallLock) {
19700                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
19701            }
19702        }
19703    }
19704
19705    @Override
19706    public void clearApplicationUserData(final String packageName,
19707            final IPackageDataObserver observer, final int userId) {
19708        mContext.enforceCallingOrSelfPermission(
19709                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
19710
19711        final int callingUid = Binder.getCallingUid();
19712        enforceCrossUserPermission(callingUid, userId,
19713                true /* requireFullPermission */, false /* checkShell */, "clear application data");
19714
19715        final PackageSetting ps = mSettings.getPackageLPr(packageName);
19716        if (ps != null && filterAppAccessLPr(ps, callingUid, userId)) {
19717            return;
19718        }
19719        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
19720            throw new SecurityException("Cannot clear data for a protected package: "
19721                    + packageName);
19722        }
19723        // Queue up an async operation since the package deletion may take a little while.
19724        mHandler.post(new Runnable() {
19725            public void run() {
19726                mHandler.removeCallbacks(this);
19727                final boolean succeeded;
19728                try (PackageFreezer freezer = freezePackage(packageName,
19729                        "clearApplicationUserData")) {
19730                    synchronized (mInstallLock) {
19731                        succeeded = clearApplicationUserDataLIF(packageName, userId);
19732                    }
19733                    clearExternalStorageDataSync(packageName, userId, true);
19734                    synchronized (mPackages) {
19735                        mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
19736                                packageName, userId);
19737                    }
19738                }
19739                if (succeeded) {
19740                    // invoke DeviceStorageMonitor's update method to clear any notifications
19741                    DeviceStorageMonitorInternal dsm = LocalServices
19742                            .getService(DeviceStorageMonitorInternal.class);
19743                    if (dsm != null) {
19744                        dsm.checkMemory();
19745                    }
19746                }
19747                if(observer != null) {
19748                    try {
19749                        observer.onRemoveCompleted(packageName, succeeded);
19750                    } catch (RemoteException e) {
19751                        Log.i(TAG, "Observer no longer exists.");
19752                    }
19753                } //end if observer
19754            } //end run
19755        });
19756    }
19757
19758    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
19759        if (packageName == null) {
19760            Slog.w(TAG, "Attempt to delete null packageName.");
19761            return false;
19762        }
19763
19764        // Try finding details about the requested package
19765        PackageParser.Package pkg;
19766        synchronized (mPackages) {
19767            pkg = mPackages.get(packageName);
19768            if (pkg == null) {
19769                final PackageSetting ps = mSettings.mPackages.get(packageName);
19770                if (ps != null) {
19771                    pkg = ps.pkg;
19772                }
19773            }
19774
19775            if (pkg == null) {
19776                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19777                return false;
19778            }
19779
19780            PackageSetting ps = (PackageSetting) pkg.mExtras;
19781            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19782        }
19783
19784        clearAppDataLIF(pkg, userId,
19785                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19786
19787        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
19788        removeKeystoreDataIfNeeded(userId, appId);
19789
19790        UserManagerInternal umInternal = getUserManagerInternal();
19791        final int flags;
19792        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
19793            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19794        } else if (umInternal.isUserRunning(userId)) {
19795            flags = StorageManager.FLAG_STORAGE_DE;
19796        } else {
19797            flags = 0;
19798        }
19799        prepareAppDataContentsLIF(pkg, userId, flags);
19800
19801        return true;
19802    }
19803
19804    /**
19805     * Reverts user permission state changes (permissions and flags) in
19806     * all packages for a given user.
19807     *
19808     * @param userId The device user for which to do a reset.
19809     */
19810    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
19811        final int packageCount = mPackages.size();
19812        for (int i = 0; i < packageCount; i++) {
19813            PackageParser.Package pkg = mPackages.valueAt(i);
19814            PackageSetting ps = (PackageSetting) pkg.mExtras;
19815            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19816        }
19817    }
19818
19819    private void resetNetworkPolicies(int userId) {
19820        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
19821    }
19822
19823    /**
19824     * Reverts user permission state changes (permissions and flags).
19825     *
19826     * @param ps The package for which to reset.
19827     * @param userId The device user for which to do a reset.
19828     */
19829    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
19830            final PackageSetting ps, final int userId) {
19831        if (ps.pkg == null) {
19832            return;
19833        }
19834
19835        // These are flags that can change base on user actions.
19836        final int userSettableMask = FLAG_PERMISSION_USER_SET
19837                | FLAG_PERMISSION_USER_FIXED
19838                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
19839                | FLAG_PERMISSION_REVIEW_REQUIRED;
19840
19841        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
19842                | FLAG_PERMISSION_POLICY_FIXED;
19843
19844        boolean writeInstallPermissions = false;
19845        boolean writeRuntimePermissions = false;
19846
19847        final int permissionCount = ps.pkg.requestedPermissions.size();
19848        for (int i = 0; i < permissionCount; i++) {
19849            String permission = ps.pkg.requestedPermissions.get(i);
19850
19851            BasePermission bp = mSettings.mPermissions.get(permission);
19852            if (bp == null) {
19853                continue;
19854            }
19855
19856            // If shared user we just reset the state to which only this app contributed.
19857            if (ps.sharedUser != null) {
19858                boolean used = false;
19859                final int packageCount = ps.sharedUser.packages.size();
19860                for (int j = 0; j < packageCount; j++) {
19861                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
19862                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
19863                            && pkg.pkg.requestedPermissions.contains(permission)) {
19864                        used = true;
19865                        break;
19866                    }
19867                }
19868                if (used) {
19869                    continue;
19870                }
19871            }
19872
19873            PermissionsState permissionsState = ps.getPermissionsState();
19874
19875            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
19876
19877            // Always clear the user settable flags.
19878            final boolean hasInstallState = permissionsState.getInstallPermissionState(
19879                    bp.name) != null;
19880            // If permission review is enabled and this is a legacy app, mark the
19881            // permission as requiring a review as this is the initial state.
19882            int flags = 0;
19883            if (mPermissionReviewRequired
19884                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
19885                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
19886            }
19887            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
19888                if (hasInstallState) {
19889                    writeInstallPermissions = true;
19890                } else {
19891                    writeRuntimePermissions = true;
19892                }
19893            }
19894
19895            // Below is only runtime permission handling.
19896            if (!bp.isRuntime()) {
19897                continue;
19898            }
19899
19900            // Never clobber system or policy.
19901            if ((oldFlags & policyOrSystemFlags) != 0) {
19902                continue;
19903            }
19904
19905            // If this permission was granted by default, make sure it is.
19906            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
19907                if (permissionsState.grantRuntimePermission(bp, userId)
19908                        != PERMISSION_OPERATION_FAILURE) {
19909                    writeRuntimePermissions = true;
19910                }
19911            // If permission review is enabled the permissions for a legacy apps
19912            // are represented as constantly granted runtime ones, so don't revoke.
19913            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
19914                // Otherwise, reset the permission.
19915                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
19916                switch (revokeResult) {
19917                    case PERMISSION_OPERATION_SUCCESS:
19918                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
19919                        writeRuntimePermissions = true;
19920                        final int appId = ps.appId;
19921                        mHandler.post(new Runnable() {
19922                            @Override
19923                            public void run() {
19924                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
19925                            }
19926                        });
19927                    } break;
19928                }
19929            }
19930        }
19931
19932        // Synchronously write as we are taking permissions away.
19933        if (writeRuntimePermissions) {
19934            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
19935        }
19936
19937        // Synchronously write as we are taking permissions away.
19938        if (writeInstallPermissions) {
19939            mSettings.writeLPr();
19940        }
19941    }
19942
19943    /**
19944     * Remove entries from the keystore daemon. Will only remove it if the
19945     * {@code appId} is valid.
19946     */
19947    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
19948        if (appId < 0) {
19949            return;
19950        }
19951
19952        final KeyStore keyStore = KeyStore.getInstance();
19953        if (keyStore != null) {
19954            if (userId == UserHandle.USER_ALL) {
19955                for (final int individual : sUserManager.getUserIds()) {
19956                    keyStore.clearUid(UserHandle.getUid(individual, appId));
19957                }
19958            } else {
19959                keyStore.clearUid(UserHandle.getUid(userId, appId));
19960            }
19961        } else {
19962            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
19963        }
19964    }
19965
19966    @Override
19967    public void deleteApplicationCacheFiles(final String packageName,
19968            final IPackageDataObserver observer) {
19969        final int userId = UserHandle.getCallingUserId();
19970        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
19971    }
19972
19973    @Override
19974    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
19975            final IPackageDataObserver observer) {
19976        final int callingUid = Binder.getCallingUid();
19977        mContext.enforceCallingOrSelfPermission(
19978                android.Manifest.permission.DELETE_CACHE_FILES, null);
19979        enforceCrossUserPermission(callingUid, userId,
19980                /* requireFullPermission= */ true, /* checkShell= */ false,
19981                "delete application cache files");
19982        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
19983                android.Manifest.permission.ACCESS_INSTANT_APPS);
19984
19985        final PackageParser.Package pkg;
19986        synchronized (mPackages) {
19987            pkg = mPackages.get(packageName);
19988        }
19989
19990        // Queue up an async operation since the package deletion may take a little while.
19991        mHandler.post(new Runnable() {
19992            public void run() {
19993                final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
19994                boolean doClearData = true;
19995                if (ps != null) {
19996                    final boolean targetIsInstantApp =
19997                            ps.getInstantApp(UserHandle.getUserId(callingUid));
19998                    doClearData = !targetIsInstantApp
19999                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
20000                }
20001                if (doClearData) {
20002                    synchronized (mInstallLock) {
20003                        final int flags = StorageManager.FLAG_STORAGE_DE
20004                                | StorageManager.FLAG_STORAGE_CE;
20005                        // We're only clearing cache files, so we don't care if the
20006                        // app is unfrozen and still able to run
20007                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
20008                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20009                    }
20010                    clearExternalStorageDataSync(packageName, userId, false);
20011                }
20012                if (observer != null) {
20013                    try {
20014                        observer.onRemoveCompleted(packageName, true);
20015                    } catch (RemoteException e) {
20016                        Log.i(TAG, "Observer no longer exists.");
20017                    }
20018                }
20019            }
20020        });
20021    }
20022
20023    @Override
20024    public void getPackageSizeInfo(final String packageName, int userHandle,
20025            final IPackageStatsObserver observer) {
20026        throw new UnsupportedOperationException(
20027                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
20028    }
20029
20030    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
20031        final PackageSetting ps;
20032        synchronized (mPackages) {
20033            ps = mSettings.mPackages.get(packageName);
20034            if (ps == null) {
20035                Slog.w(TAG, "Failed to find settings for " + packageName);
20036                return false;
20037            }
20038        }
20039
20040        final String[] packageNames = { packageName };
20041        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
20042        final String[] codePaths = { ps.codePathString };
20043
20044        try {
20045            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
20046                    ps.appId, ceDataInodes, codePaths, stats);
20047
20048            // For now, ignore code size of packages on system partition
20049            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
20050                stats.codeSize = 0;
20051            }
20052
20053            // External clients expect these to be tracked separately
20054            stats.dataSize -= stats.cacheSize;
20055
20056        } catch (InstallerException e) {
20057            Slog.w(TAG, String.valueOf(e));
20058            return false;
20059        }
20060
20061        return true;
20062    }
20063
20064    private int getUidTargetSdkVersionLockedLPr(int uid) {
20065        Object obj = mSettings.getUserIdLPr(uid);
20066        if (obj instanceof SharedUserSetting) {
20067            final SharedUserSetting sus = (SharedUserSetting) obj;
20068            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
20069            final Iterator<PackageSetting> it = sus.packages.iterator();
20070            while (it.hasNext()) {
20071                final PackageSetting ps = it.next();
20072                if (ps.pkg != null) {
20073                    int v = ps.pkg.applicationInfo.targetSdkVersion;
20074                    if (v < vers) vers = v;
20075                }
20076            }
20077            return vers;
20078        } else if (obj instanceof PackageSetting) {
20079            final PackageSetting ps = (PackageSetting) obj;
20080            if (ps.pkg != null) {
20081                return ps.pkg.applicationInfo.targetSdkVersion;
20082            }
20083        }
20084        return Build.VERSION_CODES.CUR_DEVELOPMENT;
20085    }
20086
20087    @Override
20088    public void addPreferredActivity(IntentFilter filter, int match,
20089            ComponentName[] set, ComponentName activity, int userId) {
20090        addPreferredActivityInternal(filter, match, set, activity, true, userId,
20091                "Adding preferred");
20092    }
20093
20094    private void addPreferredActivityInternal(IntentFilter filter, int match,
20095            ComponentName[] set, ComponentName activity, boolean always, int userId,
20096            String opname) {
20097        // writer
20098        int callingUid = Binder.getCallingUid();
20099        enforceCrossUserPermission(callingUid, userId,
20100                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
20101        if (filter.countActions() == 0) {
20102            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20103            return;
20104        }
20105        synchronized (mPackages) {
20106            if (mContext.checkCallingOrSelfPermission(
20107                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20108                    != PackageManager.PERMISSION_GRANTED) {
20109                if (getUidTargetSdkVersionLockedLPr(callingUid)
20110                        < Build.VERSION_CODES.FROYO) {
20111                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
20112                            + callingUid);
20113                    return;
20114                }
20115                mContext.enforceCallingOrSelfPermission(
20116                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20117            }
20118
20119            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
20120            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
20121                    + userId + ":");
20122            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20123            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
20124            scheduleWritePackageRestrictionsLocked(userId);
20125            postPreferredActivityChangedBroadcast(userId);
20126        }
20127    }
20128
20129    private void postPreferredActivityChangedBroadcast(int userId) {
20130        mHandler.post(() -> {
20131            final IActivityManager am = ActivityManager.getService();
20132            if (am == null) {
20133                return;
20134            }
20135
20136            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
20137            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
20138            try {
20139                am.broadcastIntent(null, intent, null, null,
20140                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
20141                        null, false, false, userId);
20142            } catch (RemoteException e) {
20143            }
20144        });
20145    }
20146
20147    @Override
20148    public void replacePreferredActivity(IntentFilter filter, int match,
20149            ComponentName[] set, ComponentName activity, int userId) {
20150        if (filter.countActions() != 1) {
20151            throw new IllegalArgumentException(
20152                    "replacePreferredActivity expects filter to have only 1 action.");
20153        }
20154        if (filter.countDataAuthorities() != 0
20155                || filter.countDataPaths() != 0
20156                || filter.countDataSchemes() > 1
20157                || filter.countDataTypes() != 0) {
20158            throw new IllegalArgumentException(
20159                    "replacePreferredActivity expects filter to have no data authorities, " +
20160                    "paths, or types; and at most one scheme.");
20161        }
20162
20163        final int callingUid = Binder.getCallingUid();
20164        enforceCrossUserPermission(callingUid, userId,
20165                true /* requireFullPermission */, false /* checkShell */,
20166                "replace preferred activity");
20167        synchronized (mPackages) {
20168            if (mContext.checkCallingOrSelfPermission(
20169                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20170                    != PackageManager.PERMISSION_GRANTED) {
20171                if (getUidTargetSdkVersionLockedLPr(callingUid)
20172                        < Build.VERSION_CODES.FROYO) {
20173                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
20174                            + Binder.getCallingUid());
20175                    return;
20176                }
20177                mContext.enforceCallingOrSelfPermission(
20178                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20179            }
20180
20181            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20182            if (pir != null) {
20183                // Get all of the existing entries that exactly match this filter.
20184                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
20185                if (existing != null && existing.size() == 1) {
20186                    PreferredActivity cur = existing.get(0);
20187                    if (DEBUG_PREFERRED) {
20188                        Slog.i(TAG, "Checking replace of preferred:");
20189                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20190                        if (!cur.mPref.mAlways) {
20191                            Slog.i(TAG, "  -- CUR; not mAlways!");
20192                        } else {
20193                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
20194                            Slog.i(TAG, "  -- CUR: mSet="
20195                                    + Arrays.toString(cur.mPref.mSetComponents));
20196                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
20197                            Slog.i(TAG, "  -- NEW: mMatch="
20198                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
20199                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
20200                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
20201                        }
20202                    }
20203                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
20204                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
20205                            && cur.mPref.sameSet(set)) {
20206                        // Setting the preferred activity to what it happens to be already
20207                        if (DEBUG_PREFERRED) {
20208                            Slog.i(TAG, "Replacing with same preferred activity "
20209                                    + cur.mPref.mShortComponent + " for user "
20210                                    + userId + ":");
20211                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20212                        }
20213                        return;
20214                    }
20215                }
20216
20217                if (existing != null) {
20218                    if (DEBUG_PREFERRED) {
20219                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
20220                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20221                    }
20222                    for (int i = 0; i < existing.size(); i++) {
20223                        PreferredActivity pa = existing.get(i);
20224                        if (DEBUG_PREFERRED) {
20225                            Slog.i(TAG, "Removing existing preferred activity "
20226                                    + pa.mPref.mComponent + ":");
20227                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
20228                        }
20229                        pir.removeFilter(pa);
20230                    }
20231                }
20232            }
20233            addPreferredActivityInternal(filter, match, set, activity, true, userId,
20234                    "Replacing preferred");
20235        }
20236    }
20237
20238    @Override
20239    public void clearPackagePreferredActivities(String packageName) {
20240        final int callingUid = Binder.getCallingUid();
20241        if (getInstantAppPackageName(callingUid) != null) {
20242            return;
20243        }
20244        // writer
20245        synchronized (mPackages) {
20246            PackageParser.Package pkg = mPackages.get(packageName);
20247            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
20248                if (mContext.checkCallingOrSelfPermission(
20249                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20250                        != PackageManager.PERMISSION_GRANTED) {
20251                    if (getUidTargetSdkVersionLockedLPr(callingUid)
20252                            < Build.VERSION_CODES.FROYO) {
20253                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
20254                                + callingUid);
20255                        return;
20256                    }
20257                    mContext.enforceCallingOrSelfPermission(
20258                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20259                }
20260            }
20261            final PackageSetting ps = mSettings.getPackageLPr(packageName);
20262            if (ps != null
20263                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20264                return;
20265            }
20266            int user = UserHandle.getCallingUserId();
20267            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
20268                scheduleWritePackageRestrictionsLocked(user);
20269            }
20270        }
20271    }
20272
20273    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20274    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
20275        ArrayList<PreferredActivity> removed = null;
20276        boolean changed = false;
20277        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20278            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
20279            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20280            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
20281                continue;
20282            }
20283            Iterator<PreferredActivity> it = pir.filterIterator();
20284            while (it.hasNext()) {
20285                PreferredActivity pa = it.next();
20286                // Mark entry for removal only if it matches the package name
20287                // and the entry is of type "always".
20288                if (packageName == null ||
20289                        (pa.mPref.mComponent.getPackageName().equals(packageName)
20290                                && pa.mPref.mAlways)) {
20291                    if (removed == null) {
20292                        removed = new ArrayList<PreferredActivity>();
20293                    }
20294                    removed.add(pa);
20295                }
20296            }
20297            if (removed != null) {
20298                for (int j=0; j<removed.size(); j++) {
20299                    PreferredActivity pa = removed.get(j);
20300                    pir.removeFilter(pa);
20301                }
20302                changed = true;
20303            }
20304        }
20305        if (changed) {
20306            postPreferredActivityChangedBroadcast(userId);
20307        }
20308        return changed;
20309    }
20310
20311    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20312    private void clearIntentFilterVerificationsLPw(int userId) {
20313        final int packageCount = mPackages.size();
20314        for (int i = 0; i < packageCount; i++) {
20315            PackageParser.Package pkg = mPackages.valueAt(i);
20316            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
20317        }
20318    }
20319
20320    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20321    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
20322        if (userId == UserHandle.USER_ALL) {
20323            if (mSettings.removeIntentFilterVerificationLPw(packageName,
20324                    sUserManager.getUserIds())) {
20325                for (int oneUserId : sUserManager.getUserIds()) {
20326                    scheduleWritePackageRestrictionsLocked(oneUserId);
20327                }
20328            }
20329        } else {
20330            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
20331                scheduleWritePackageRestrictionsLocked(userId);
20332            }
20333        }
20334    }
20335
20336    /** Clears state for all users, and touches intent filter verification policy */
20337    void clearDefaultBrowserIfNeeded(String packageName) {
20338        for (int oneUserId : sUserManager.getUserIds()) {
20339            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
20340        }
20341    }
20342
20343    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
20344        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
20345        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
20346            if (packageName.equals(defaultBrowserPackageName)) {
20347                setDefaultBrowserPackageName(null, userId);
20348            }
20349        }
20350    }
20351
20352    @Override
20353    public void resetApplicationPreferences(int userId) {
20354        mContext.enforceCallingOrSelfPermission(
20355                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20356        final long identity = Binder.clearCallingIdentity();
20357        // writer
20358        try {
20359            synchronized (mPackages) {
20360                clearPackagePreferredActivitiesLPw(null, userId);
20361                mSettings.applyDefaultPreferredAppsLPw(this, userId);
20362                // TODO: We have to reset the default SMS and Phone. This requires
20363                // significant refactoring to keep all default apps in the package
20364                // manager (cleaner but more work) or have the services provide
20365                // callbacks to the package manager to request a default app reset.
20366                applyFactoryDefaultBrowserLPw(userId);
20367                clearIntentFilterVerificationsLPw(userId);
20368                primeDomainVerificationsLPw(userId);
20369                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
20370                scheduleWritePackageRestrictionsLocked(userId);
20371            }
20372            resetNetworkPolicies(userId);
20373        } finally {
20374            Binder.restoreCallingIdentity(identity);
20375        }
20376    }
20377
20378    @Override
20379    public int getPreferredActivities(List<IntentFilter> outFilters,
20380            List<ComponentName> outActivities, String packageName) {
20381        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20382            return 0;
20383        }
20384        int num = 0;
20385        final int userId = UserHandle.getCallingUserId();
20386        // reader
20387        synchronized (mPackages) {
20388            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20389            if (pir != null) {
20390                final Iterator<PreferredActivity> it = pir.filterIterator();
20391                while (it.hasNext()) {
20392                    final PreferredActivity pa = it.next();
20393                    if (packageName == null
20394                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
20395                                    && pa.mPref.mAlways)) {
20396                        if (outFilters != null) {
20397                            outFilters.add(new IntentFilter(pa));
20398                        }
20399                        if (outActivities != null) {
20400                            outActivities.add(pa.mPref.mComponent);
20401                        }
20402                    }
20403                }
20404            }
20405        }
20406
20407        return num;
20408    }
20409
20410    @Override
20411    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
20412            int userId) {
20413        int callingUid = Binder.getCallingUid();
20414        if (callingUid != Process.SYSTEM_UID) {
20415            throw new SecurityException(
20416                    "addPersistentPreferredActivity can only be run by the system");
20417        }
20418        if (filter.countActions() == 0) {
20419            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20420            return;
20421        }
20422        synchronized (mPackages) {
20423            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
20424                    ":");
20425            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20426            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
20427                    new PersistentPreferredActivity(filter, activity));
20428            scheduleWritePackageRestrictionsLocked(userId);
20429            postPreferredActivityChangedBroadcast(userId);
20430        }
20431    }
20432
20433    @Override
20434    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
20435        int callingUid = Binder.getCallingUid();
20436        if (callingUid != Process.SYSTEM_UID) {
20437            throw new SecurityException(
20438                    "clearPackagePersistentPreferredActivities can only be run by the system");
20439        }
20440        ArrayList<PersistentPreferredActivity> removed = null;
20441        boolean changed = false;
20442        synchronized (mPackages) {
20443            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
20444                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
20445                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
20446                        .valueAt(i);
20447                if (userId != thisUserId) {
20448                    continue;
20449                }
20450                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
20451                while (it.hasNext()) {
20452                    PersistentPreferredActivity ppa = it.next();
20453                    // Mark entry for removal only if it matches the package name.
20454                    if (ppa.mComponent.getPackageName().equals(packageName)) {
20455                        if (removed == null) {
20456                            removed = new ArrayList<PersistentPreferredActivity>();
20457                        }
20458                        removed.add(ppa);
20459                    }
20460                }
20461                if (removed != null) {
20462                    for (int j=0; j<removed.size(); j++) {
20463                        PersistentPreferredActivity ppa = removed.get(j);
20464                        ppir.removeFilter(ppa);
20465                    }
20466                    changed = true;
20467                }
20468            }
20469
20470            if (changed) {
20471                scheduleWritePackageRestrictionsLocked(userId);
20472                postPreferredActivityChangedBroadcast(userId);
20473            }
20474        }
20475    }
20476
20477    /**
20478     * Common machinery for picking apart a restored XML blob and passing
20479     * it to a caller-supplied functor to be applied to the running system.
20480     */
20481    private void restoreFromXml(XmlPullParser parser, int userId,
20482            String expectedStartTag, BlobXmlRestorer functor)
20483            throws IOException, XmlPullParserException {
20484        int type;
20485        while ((type = parser.next()) != XmlPullParser.START_TAG
20486                && type != XmlPullParser.END_DOCUMENT) {
20487        }
20488        if (type != XmlPullParser.START_TAG) {
20489            // oops didn't find a start tag?!
20490            if (DEBUG_BACKUP) {
20491                Slog.e(TAG, "Didn't find start tag during restore");
20492            }
20493            return;
20494        }
20495Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
20496        // this is supposed to be TAG_PREFERRED_BACKUP
20497        if (!expectedStartTag.equals(parser.getName())) {
20498            if (DEBUG_BACKUP) {
20499                Slog.e(TAG, "Found unexpected tag " + parser.getName());
20500            }
20501            return;
20502        }
20503
20504        // skip interfering stuff, then we're aligned with the backing implementation
20505        while ((type = parser.next()) == XmlPullParser.TEXT) { }
20506Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
20507        functor.apply(parser, userId);
20508    }
20509
20510    private interface BlobXmlRestorer {
20511        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
20512    }
20513
20514    /**
20515     * Non-Binder method, support for the backup/restore mechanism: write the
20516     * full set of preferred activities in its canonical XML format.  Returns the
20517     * XML output as a byte array, or null if there is none.
20518     */
20519    @Override
20520    public byte[] getPreferredActivityBackup(int userId) {
20521        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20522            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
20523        }
20524
20525        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20526        try {
20527            final XmlSerializer serializer = new FastXmlSerializer();
20528            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20529            serializer.startDocument(null, true);
20530            serializer.startTag(null, TAG_PREFERRED_BACKUP);
20531
20532            synchronized (mPackages) {
20533                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
20534            }
20535
20536            serializer.endTag(null, TAG_PREFERRED_BACKUP);
20537            serializer.endDocument();
20538            serializer.flush();
20539        } catch (Exception e) {
20540            if (DEBUG_BACKUP) {
20541                Slog.e(TAG, "Unable to write preferred activities for backup", e);
20542            }
20543            return null;
20544        }
20545
20546        return dataStream.toByteArray();
20547    }
20548
20549    @Override
20550    public void restorePreferredActivities(byte[] backup, int userId) {
20551        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20552            throw new SecurityException("Only the system may call restorePreferredActivities()");
20553        }
20554
20555        try {
20556            final XmlPullParser parser = Xml.newPullParser();
20557            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20558            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
20559                    new BlobXmlRestorer() {
20560                        @Override
20561                        public void apply(XmlPullParser parser, int userId)
20562                                throws XmlPullParserException, IOException {
20563                            synchronized (mPackages) {
20564                                mSettings.readPreferredActivitiesLPw(parser, userId);
20565                            }
20566                        }
20567                    } );
20568        } catch (Exception e) {
20569            if (DEBUG_BACKUP) {
20570                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20571            }
20572        }
20573    }
20574
20575    /**
20576     * Non-Binder method, support for the backup/restore mechanism: write the
20577     * default browser (etc) settings in its canonical XML format.  Returns the default
20578     * browser XML representation as a byte array, or null if there is none.
20579     */
20580    @Override
20581    public byte[] getDefaultAppsBackup(int userId) {
20582        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20583            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
20584        }
20585
20586        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20587        try {
20588            final XmlSerializer serializer = new FastXmlSerializer();
20589            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20590            serializer.startDocument(null, true);
20591            serializer.startTag(null, TAG_DEFAULT_APPS);
20592
20593            synchronized (mPackages) {
20594                mSettings.writeDefaultAppsLPr(serializer, userId);
20595            }
20596
20597            serializer.endTag(null, TAG_DEFAULT_APPS);
20598            serializer.endDocument();
20599            serializer.flush();
20600        } catch (Exception e) {
20601            if (DEBUG_BACKUP) {
20602                Slog.e(TAG, "Unable to write default apps for backup", e);
20603            }
20604            return null;
20605        }
20606
20607        return dataStream.toByteArray();
20608    }
20609
20610    @Override
20611    public void restoreDefaultApps(byte[] backup, int userId) {
20612        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20613            throw new SecurityException("Only the system may call restoreDefaultApps()");
20614        }
20615
20616        try {
20617            final XmlPullParser parser = Xml.newPullParser();
20618            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20619            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
20620                    new BlobXmlRestorer() {
20621                        @Override
20622                        public void apply(XmlPullParser parser, int userId)
20623                                throws XmlPullParserException, IOException {
20624                            synchronized (mPackages) {
20625                                mSettings.readDefaultAppsLPw(parser, userId);
20626                            }
20627                        }
20628                    } );
20629        } catch (Exception e) {
20630            if (DEBUG_BACKUP) {
20631                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
20632            }
20633        }
20634    }
20635
20636    @Override
20637    public byte[] getIntentFilterVerificationBackup(int userId) {
20638        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20639            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
20640        }
20641
20642        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20643        try {
20644            final XmlSerializer serializer = new FastXmlSerializer();
20645            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20646            serializer.startDocument(null, true);
20647            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
20648
20649            synchronized (mPackages) {
20650                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
20651            }
20652
20653            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
20654            serializer.endDocument();
20655            serializer.flush();
20656        } catch (Exception e) {
20657            if (DEBUG_BACKUP) {
20658                Slog.e(TAG, "Unable to write default apps for backup", e);
20659            }
20660            return null;
20661        }
20662
20663        return dataStream.toByteArray();
20664    }
20665
20666    @Override
20667    public void restoreIntentFilterVerification(byte[] backup, int userId) {
20668        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20669            throw new SecurityException("Only the system may call restorePreferredActivities()");
20670        }
20671
20672        try {
20673            final XmlPullParser parser = Xml.newPullParser();
20674            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20675            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
20676                    new BlobXmlRestorer() {
20677                        @Override
20678                        public void apply(XmlPullParser parser, int userId)
20679                                throws XmlPullParserException, IOException {
20680                            synchronized (mPackages) {
20681                                mSettings.readAllDomainVerificationsLPr(parser, userId);
20682                                mSettings.writeLPr();
20683                            }
20684                        }
20685                    } );
20686        } catch (Exception e) {
20687            if (DEBUG_BACKUP) {
20688                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20689            }
20690        }
20691    }
20692
20693    @Override
20694    public byte[] getPermissionGrantBackup(int userId) {
20695        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20696            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
20697        }
20698
20699        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20700        try {
20701            final XmlSerializer serializer = new FastXmlSerializer();
20702            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20703            serializer.startDocument(null, true);
20704            serializer.startTag(null, TAG_PERMISSION_BACKUP);
20705
20706            synchronized (mPackages) {
20707                serializeRuntimePermissionGrantsLPr(serializer, userId);
20708            }
20709
20710            serializer.endTag(null, TAG_PERMISSION_BACKUP);
20711            serializer.endDocument();
20712            serializer.flush();
20713        } catch (Exception e) {
20714            if (DEBUG_BACKUP) {
20715                Slog.e(TAG, "Unable to write default apps for backup", e);
20716            }
20717            return null;
20718        }
20719
20720        return dataStream.toByteArray();
20721    }
20722
20723    @Override
20724    public void restorePermissionGrants(byte[] backup, int userId) {
20725        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20726            throw new SecurityException("Only the system may call restorePermissionGrants()");
20727        }
20728
20729        try {
20730            final XmlPullParser parser = Xml.newPullParser();
20731            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20732            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
20733                    new BlobXmlRestorer() {
20734                        @Override
20735                        public void apply(XmlPullParser parser, int userId)
20736                                throws XmlPullParserException, IOException {
20737                            synchronized (mPackages) {
20738                                processRestoredPermissionGrantsLPr(parser, userId);
20739                            }
20740                        }
20741                    } );
20742        } catch (Exception e) {
20743            if (DEBUG_BACKUP) {
20744                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20745            }
20746        }
20747    }
20748
20749    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
20750            throws IOException {
20751        serializer.startTag(null, TAG_ALL_GRANTS);
20752
20753        final int N = mSettings.mPackages.size();
20754        for (int i = 0; i < N; i++) {
20755            final PackageSetting ps = mSettings.mPackages.valueAt(i);
20756            boolean pkgGrantsKnown = false;
20757
20758            PermissionsState packagePerms = ps.getPermissionsState();
20759
20760            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
20761                final int grantFlags = state.getFlags();
20762                // only look at grants that are not system/policy fixed
20763                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
20764                    final boolean isGranted = state.isGranted();
20765                    // And only back up the user-twiddled state bits
20766                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
20767                        final String packageName = mSettings.mPackages.keyAt(i);
20768                        if (!pkgGrantsKnown) {
20769                            serializer.startTag(null, TAG_GRANT);
20770                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
20771                            pkgGrantsKnown = true;
20772                        }
20773
20774                        final boolean userSet =
20775                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
20776                        final boolean userFixed =
20777                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
20778                        final boolean revoke =
20779                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
20780
20781                        serializer.startTag(null, TAG_PERMISSION);
20782                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
20783                        if (isGranted) {
20784                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
20785                        }
20786                        if (userSet) {
20787                            serializer.attribute(null, ATTR_USER_SET, "true");
20788                        }
20789                        if (userFixed) {
20790                            serializer.attribute(null, ATTR_USER_FIXED, "true");
20791                        }
20792                        if (revoke) {
20793                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
20794                        }
20795                        serializer.endTag(null, TAG_PERMISSION);
20796                    }
20797                }
20798            }
20799
20800            if (pkgGrantsKnown) {
20801                serializer.endTag(null, TAG_GRANT);
20802            }
20803        }
20804
20805        serializer.endTag(null, TAG_ALL_GRANTS);
20806    }
20807
20808    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
20809            throws XmlPullParserException, IOException {
20810        String pkgName = null;
20811        int outerDepth = parser.getDepth();
20812        int type;
20813        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
20814                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
20815            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
20816                continue;
20817            }
20818
20819            final String tagName = parser.getName();
20820            if (tagName.equals(TAG_GRANT)) {
20821                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
20822                if (DEBUG_BACKUP) {
20823                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
20824                }
20825            } else if (tagName.equals(TAG_PERMISSION)) {
20826
20827                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
20828                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
20829
20830                int newFlagSet = 0;
20831                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
20832                    newFlagSet |= FLAG_PERMISSION_USER_SET;
20833                }
20834                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
20835                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
20836                }
20837                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
20838                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
20839                }
20840                if (DEBUG_BACKUP) {
20841                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
20842                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
20843                }
20844                final PackageSetting ps = mSettings.mPackages.get(pkgName);
20845                if (ps != null) {
20846                    // Already installed so we apply the grant immediately
20847                    if (DEBUG_BACKUP) {
20848                        Slog.v(TAG, "        + already installed; applying");
20849                    }
20850                    PermissionsState perms = ps.getPermissionsState();
20851                    BasePermission bp = mSettings.mPermissions.get(permName);
20852                    if (bp != null) {
20853                        if (isGranted) {
20854                            perms.grantRuntimePermission(bp, userId);
20855                        }
20856                        if (newFlagSet != 0) {
20857                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
20858                        }
20859                    }
20860                } else {
20861                    // Need to wait for post-restore install to apply the grant
20862                    if (DEBUG_BACKUP) {
20863                        Slog.v(TAG, "        - not yet installed; saving for later");
20864                    }
20865                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
20866                            isGranted, newFlagSet, userId);
20867                }
20868            } else {
20869                PackageManagerService.reportSettingsProblem(Log.WARN,
20870                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
20871                XmlUtils.skipCurrentTag(parser);
20872            }
20873        }
20874
20875        scheduleWriteSettingsLocked();
20876        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
20877    }
20878
20879    @Override
20880    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
20881            int sourceUserId, int targetUserId, int flags) {
20882        mContext.enforceCallingOrSelfPermission(
20883                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20884        int callingUid = Binder.getCallingUid();
20885        enforceOwnerRights(ownerPackage, callingUid);
20886        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20887        if (intentFilter.countActions() == 0) {
20888            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
20889            return;
20890        }
20891        synchronized (mPackages) {
20892            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
20893                    ownerPackage, targetUserId, flags);
20894            CrossProfileIntentResolver resolver =
20895                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20896            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
20897            // We have all those whose filter is equal. Now checking if the rest is equal as well.
20898            if (existing != null) {
20899                int size = existing.size();
20900                for (int i = 0; i < size; i++) {
20901                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
20902                        return;
20903                    }
20904                }
20905            }
20906            resolver.addFilter(newFilter);
20907            scheduleWritePackageRestrictionsLocked(sourceUserId);
20908        }
20909    }
20910
20911    @Override
20912    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
20913        mContext.enforceCallingOrSelfPermission(
20914                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20915        final int callingUid = Binder.getCallingUid();
20916        enforceOwnerRights(ownerPackage, callingUid);
20917        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20918        synchronized (mPackages) {
20919            CrossProfileIntentResolver resolver =
20920                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20921            ArraySet<CrossProfileIntentFilter> set =
20922                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
20923            for (CrossProfileIntentFilter filter : set) {
20924                if (filter.getOwnerPackage().equals(ownerPackage)) {
20925                    resolver.removeFilter(filter);
20926                }
20927            }
20928            scheduleWritePackageRestrictionsLocked(sourceUserId);
20929        }
20930    }
20931
20932    // Enforcing that callingUid is owning pkg on userId
20933    private void enforceOwnerRights(String pkg, int callingUid) {
20934        // The system owns everything.
20935        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
20936            return;
20937        }
20938        final int callingUserId = UserHandle.getUserId(callingUid);
20939        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
20940        if (pi == null) {
20941            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
20942                    + callingUserId);
20943        }
20944        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
20945            throw new SecurityException("Calling uid " + callingUid
20946                    + " does not own package " + pkg);
20947        }
20948    }
20949
20950    @Override
20951    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
20952        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20953            return null;
20954        }
20955        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
20956    }
20957
20958    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
20959        UserManagerService ums = UserManagerService.getInstance();
20960        if (ums != null) {
20961            final UserInfo parent = ums.getProfileParent(userId);
20962            final int launcherUid = (parent != null) ? parent.id : userId;
20963            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
20964            if (launcherComponent != null) {
20965                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
20966                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
20967                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
20968                        .setPackage(launcherComponent.getPackageName());
20969                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
20970            }
20971        }
20972    }
20973
20974    /**
20975     * Report the 'Home' activity which is currently set as "always use this one". If non is set
20976     * then reports the most likely home activity or null if there are more than one.
20977     */
20978    private ComponentName getDefaultHomeActivity(int userId) {
20979        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
20980        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
20981        if (cn != null) {
20982            return cn;
20983        }
20984
20985        // Find the launcher with the highest priority and return that component if there are no
20986        // other home activity with the same priority.
20987        int lastPriority = Integer.MIN_VALUE;
20988        ComponentName lastComponent = null;
20989        final int size = allHomeCandidates.size();
20990        for (int i = 0; i < size; i++) {
20991            final ResolveInfo ri = allHomeCandidates.get(i);
20992            if (ri.priority > lastPriority) {
20993                lastComponent = ri.activityInfo.getComponentName();
20994                lastPriority = ri.priority;
20995            } else if (ri.priority == lastPriority) {
20996                // Two components found with same priority.
20997                lastComponent = null;
20998            }
20999        }
21000        return lastComponent;
21001    }
21002
21003    private Intent getHomeIntent() {
21004        Intent intent = new Intent(Intent.ACTION_MAIN);
21005        intent.addCategory(Intent.CATEGORY_HOME);
21006        intent.addCategory(Intent.CATEGORY_DEFAULT);
21007        return intent;
21008    }
21009
21010    private IntentFilter getHomeFilter() {
21011        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
21012        filter.addCategory(Intent.CATEGORY_HOME);
21013        filter.addCategory(Intent.CATEGORY_DEFAULT);
21014        return filter;
21015    }
21016
21017    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
21018            int userId) {
21019        Intent intent  = getHomeIntent();
21020        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
21021                PackageManager.GET_META_DATA, userId);
21022        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
21023                true, false, false, userId);
21024
21025        allHomeCandidates.clear();
21026        if (list != null) {
21027            for (ResolveInfo ri : list) {
21028                allHomeCandidates.add(ri);
21029            }
21030        }
21031        return (preferred == null || preferred.activityInfo == null)
21032                ? null
21033                : new ComponentName(preferred.activityInfo.packageName,
21034                        preferred.activityInfo.name);
21035    }
21036
21037    @Override
21038    public void setHomeActivity(ComponentName comp, int userId) {
21039        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21040            return;
21041        }
21042        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
21043        getHomeActivitiesAsUser(homeActivities, userId);
21044
21045        boolean found = false;
21046
21047        final int size = homeActivities.size();
21048        final ComponentName[] set = new ComponentName[size];
21049        for (int i = 0; i < size; i++) {
21050            final ResolveInfo candidate = homeActivities.get(i);
21051            final ActivityInfo info = candidate.activityInfo;
21052            final ComponentName activityName = new ComponentName(info.packageName, info.name);
21053            set[i] = activityName;
21054            if (!found && activityName.equals(comp)) {
21055                found = true;
21056            }
21057        }
21058        if (!found) {
21059            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
21060                    + userId);
21061        }
21062        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
21063                set, comp, userId);
21064    }
21065
21066    private @Nullable String getSetupWizardPackageName() {
21067        final Intent intent = new Intent(Intent.ACTION_MAIN);
21068        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
21069
21070        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21071                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21072                        | MATCH_DISABLED_COMPONENTS,
21073                UserHandle.myUserId());
21074        if (matches.size() == 1) {
21075            return matches.get(0).getComponentInfo().packageName;
21076        } else {
21077            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
21078                    + ": matches=" + matches);
21079            return null;
21080        }
21081    }
21082
21083    private @Nullable String getStorageManagerPackageName() {
21084        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
21085
21086        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21087                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21088                        | MATCH_DISABLED_COMPONENTS,
21089                UserHandle.myUserId());
21090        if (matches.size() == 1) {
21091            return matches.get(0).getComponentInfo().packageName;
21092        } else {
21093            Slog.e(TAG, "There should probably be exactly one storage manager; found "
21094                    + matches.size() + ": matches=" + matches);
21095            return null;
21096        }
21097    }
21098
21099    @Override
21100    public void setApplicationEnabledSetting(String appPackageName,
21101            int newState, int flags, int userId, String callingPackage) {
21102        if (!sUserManager.exists(userId)) return;
21103        if (callingPackage == null) {
21104            callingPackage = Integer.toString(Binder.getCallingUid());
21105        }
21106        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
21107    }
21108
21109    @Override
21110    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
21111        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
21112        synchronized (mPackages) {
21113            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
21114            if (pkgSetting != null) {
21115                pkgSetting.setUpdateAvailable(updateAvailable);
21116            }
21117        }
21118    }
21119
21120    @Override
21121    public void setComponentEnabledSetting(ComponentName componentName,
21122            int newState, int flags, int userId) {
21123        if (!sUserManager.exists(userId)) return;
21124        setEnabledSetting(componentName.getPackageName(),
21125                componentName.getClassName(), newState, flags, userId, null);
21126    }
21127
21128    private void setEnabledSetting(final String packageName, String className, int newState,
21129            final int flags, int userId, String callingPackage) {
21130        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
21131              || newState == COMPONENT_ENABLED_STATE_ENABLED
21132              || newState == COMPONENT_ENABLED_STATE_DISABLED
21133              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21134              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
21135            throw new IllegalArgumentException("Invalid new component state: "
21136                    + newState);
21137        }
21138        PackageSetting pkgSetting;
21139        final int callingUid = Binder.getCallingUid();
21140        final int permission;
21141        if (callingUid == Process.SYSTEM_UID) {
21142            permission = PackageManager.PERMISSION_GRANTED;
21143        } else {
21144            permission = mContext.checkCallingOrSelfPermission(
21145                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21146        }
21147        enforceCrossUserPermission(callingUid, userId,
21148                false /* requireFullPermission */, true /* checkShell */, "set enabled");
21149        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21150        boolean sendNow = false;
21151        boolean isApp = (className == null);
21152        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
21153        String componentName = isApp ? packageName : className;
21154        int packageUid = -1;
21155        ArrayList<String> components;
21156
21157        // reader
21158        synchronized (mPackages) {
21159            pkgSetting = mSettings.mPackages.get(packageName);
21160            if (pkgSetting == null) {
21161                if (!isCallerInstantApp) {
21162                    if (className == null) {
21163                        throw new IllegalArgumentException("Unknown package: " + packageName);
21164                    }
21165                    throw new IllegalArgumentException(
21166                            "Unknown component: " + packageName + "/" + className);
21167                } else {
21168                    // throw SecurityException to prevent leaking package information
21169                    throw new SecurityException(
21170                            "Attempt to change component state; "
21171                            + "pid=" + Binder.getCallingPid()
21172                            + ", uid=" + callingUid
21173                            + (className == null
21174                                    ? ", package=" + packageName
21175                                    : ", component=" + packageName + "/" + className));
21176                }
21177            }
21178        }
21179
21180        // Limit who can change which apps
21181        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
21182            // Don't allow apps that don't have permission to modify other apps
21183            if (!allowedByPermission
21184                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
21185                throw new SecurityException(
21186                        "Attempt to change component state; "
21187                        + "pid=" + Binder.getCallingPid()
21188                        + ", uid=" + callingUid
21189                        + (className == null
21190                                ? ", package=" + packageName
21191                                : ", component=" + packageName + "/" + className));
21192            }
21193            // Don't allow changing protected packages.
21194            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
21195                throw new SecurityException("Cannot disable a protected package: " + packageName);
21196            }
21197        }
21198
21199        synchronized (mPackages) {
21200            if (callingUid == Process.SHELL_UID
21201                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
21202                // Shell can only change whole packages between ENABLED and DISABLED_USER states
21203                // unless it is a test package.
21204                int oldState = pkgSetting.getEnabled(userId);
21205                if (className == null
21206                    &&
21207                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
21208                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
21209                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
21210                    &&
21211                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21212                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
21213                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
21214                    // ok
21215                } else {
21216                    throw new SecurityException(
21217                            "Shell cannot change component state for " + packageName + "/"
21218                            + className + " to " + newState);
21219                }
21220            }
21221            if (className == null) {
21222                // We're dealing with an application/package level state change
21223                if (pkgSetting.getEnabled(userId) == newState) {
21224                    // Nothing to do
21225                    return;
21226                }
21227                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
21228                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
21229                    // Don't care about who enables an app.
21230                    callingPackage = null;
21231                }
21232                pkgSetting.setEnabled(newState, userId, callingPackage);
21233                // pkgSetting.pkg.mSetEnabled = newState;
21234            } else {
21235                // We're dealing with a component level state change
21236                // First, verify that this is a valid class name.
21237                PackageParser.Package pkg = pkgSetting.pkg;
21238                if (pkg == null || !pkg.hasComponentClassName(className)) {
21239                    if (pkg != null &&
21240                            pkg.applicationInfo.targetSdkVersion >=
21241                                    Build.VERSION_CODES.JELLY_BEAN) {
21242                        throw new IllegalArgumentException("Component class " + className
21243                                + " does not exist in " + packageName);
21244                    } else {
21245                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
21246                                + className + " does not exist in " + packageName);
21247                    }
21248                }
21249                switch (newState) {
21250                case COMPONENT_ENABLED_STATE_ENABLED:
21251                    if (!pkgSetting.enableComponentLPw(className, userId)) {
21252                        return;
21253                    }
21254                    break;
21255                case COMPONENT_ENABLED_STATE_DISABLED:
21256                    if (!pkgSetting.disableComponentLPw(className, userId)) {
21257                        return;
21258                    }
21259                    break;
21260                case COMPONENT_ENABLED_STATE_DEFAULT:
21261                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
21262                        return;
21263                    }
21264                    break;
21265                default:
21266                    Slog.e(TAG, "Invalid new component state: " + newState);
21267                    return;
21268                }
21269            }
21270            scheduleWritePackageRestrictionsLocked(userId);
21271            updateSequenceNumberLP(pkgSetting, new int[] { userId });
21272            final long callingId = Binder.clearCallingIdentity();
21273            try {
21274                updateInstantAppInstallerLocked(packageName);
21275            } finally {
21276                Binder.restoreCallingIdentity(callingId);
21277            }
21278            components = mPendingBroadcasts.get(userId, packageName);
21279            final boolean newPackage = components == null;
21280            if (newPackage) {
21281                components = new ArrayList<String>();
21282            }
21283            if (!components.contains(componentName)) {
21284                components.add(componentName);
21285            }
21286            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
21287                sendNow = true;
21288                // Purge entry from pending broadcast list if another one exists already
21289                // since we are sending one right away.
21290                mPendingBroadcasts.remove(userId, packageName);
21291            } else {
21292                if (newPackage) {
21293                    mPendingBroadcasts.put(userId, packageName, components);
21294                }
21295                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
21296                    // Schedule a message
21297                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
21298                }
21299            }
21300        }
21301
21302        long callingId = Binder.clearCallingIdentity();
21303        try {
21304            if (sendNow) {
21305                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
21306                sendPackageChangedBroadcast(packageName,
21307                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
21308            }
21309        } finally {
21310            Binder.restoreCallingIdentity(callingId);
21311        }
21312    }
21313
21314    @Override
21315    public void flushPackageRestrictionsAsUser(int userId) {
21316        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21317            return;
21318        }
21319        if (!sUserManager.exists(userId)) {
21320            return;
21321        }
21322        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
21323                false /* checkShell */, "flushPackageRestrictions");
21324        synchronized (mPackages) {
21325            mSettings.writePackageRestrictionsLPr(userId);
21326            mDirtyUsers.remove(userId);
21327            if (mDirtyUsers.isEmpty()) {
21328                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
21329            }
21330        }
21331    }
21332
21333    private void sendPackageChangedBroadcast(String packageName,
21334            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
21335        if (DEBUG_INSTALL)
21336            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
21337                    + componentNames);
21338        Bundle extras = new Bundle(4);
21339        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
21340        String nameList[] = new String[componentNames.size()];
21341        componentNames.toArray(nameList);
21342        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
21343        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
21344        extras.putInt(Intent.EXTRA_UID, packageUid);
21345        // If this is not reporting a change of the overall package, then only send it
21346        // to registered receivers.  We don't want to launch a swath of apps for every
21347        // little component state change.
21348        final int flags = !componentNames.contains(packageName)
21349                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
21350        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
21351                new int[] {UserHandle.getUserId(packageUid)});
21352    }
21353
21354    @Override
21355    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
21356        if (!sUserManager.exists(userId)) return;
21357        final int callingUid = Binder.getCallingUid();
21358        if (getInstantAppPackageName(callingUid) != null) {
21359            return;
21360        }
21361        final int permission = mContext.checkCallingOrSelfPermission(
21362                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21363        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21364        enforceCrossUserPermission(callingUid, userId,
21365                true /* requireFullPermission */, true /* checkShell */, "stop package");
21366        // writer
21367        synchronized (mPackages) {
21368            final PackageSetting ps = mSettings.mPackages.get(packageName);
21369            if (!filterAppAccessLPr(ps, callingUid, userId)
21370                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
21371                            allowedByPermission, callingUid, userId)) {
21372                scheduleWritePackageRestrictionsLocked(userId);
21373            }
21374        }
21375    }
21376
21377    @Override
21378    public String getInstallerPackageName(String packageName) {
21379        final int callingUid = Binder.getCallingUid();
21380        if (getInstantAppPackageName(callingUid) != null) {
21381            return null;
21382        }
21383        // reader
21384        synchronized (mPackages) {
21385            final PackageSetting ps = mSettings.mPackages.get(packageName);
21386            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
21387                return null;
21388            }
21389            return mSettings.getInstallerPackageNameLPr(packageName);
21390        }
21391    }
21392
21393    public boolean isOrphaned(String packageName) {
21394        // reader
21395        synchronized (mPackages) {
21396            return mSettings.isOrphaned(packageName);
21397        }
21398    }
21399
21400    @Override
21401    public int getApplicationEnabledSetting(String packageName, int userId) {
21402        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
21403        int callingUid = Binder.getCallingUid();
21404        enforceCrossUserPermission(callingUid, userId,
21405                false /* requireFullPermission */, false /* checkShell */, "get enabled");
21406        // reader
21407        synchronized (mPackages) {
21408            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
21409                return COMPONENT_ENABLED_STATE_DISABLED;
21410            }
21411            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
21412        }
21413    }
21414
21415    @Override
21416    public int getComponentEnabledSetting(ComponentName component, int userId) {
21417        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
21418        int callingUid = Binder.getCallingUid();
21419        enforceCrossUserPermission(callingUid, userId,
21420                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
21421        synchronized (mPackages) {
21422            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
21423                    component, TYPE_UNKNOWN, userId)) {
21424                return COMPONENT_ENABLED_STATE_DISABLED;
21425            }
21426            return mSettings.getComponentEnabledSettingLPr(component, userId);
21427        }
21428    }
21429
21430    @Override
21431    public void enterSafeMode() {
21432        enforceSystemOrRoot("Only the system can request entering safe mode");
21433
21434        if (!mSystemReady) {
21435            mSafeMode = true;
21436        }
21437    }
21438
21439    @Override
21440    public void systemReady() {
21441        enforceSystemOrRoot("Only the system can claim the system is ready");
21442
21443        mSystemReady = true;
21444        final ContentResolver resolver = mContext.getContentResolver();
21445        ContentObserver co = new ContentObserver(mHandler) {
21446            @Override
21447            public void onChange(boolean selfChange) {
21448                mEphemeralAppsDisabled =
21449                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
21450                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
21451            }
21452        };
21453        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
21454                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
21455                false, co, UserHandle.USER_SYSTEM);
21456        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
21457                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
21458        co.onChange(true);
21459
21460        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
21461        // disabled after already being started.
21462        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
21463                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
21464
21465        // Read the compatibilty setting when the system is ready.
21466        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
21467                mContext.getContentResolver(),
21468                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
21469        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
21470        if (DEBUG_SETTINGS) {
21471            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
21472        }
21473
21474        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
21475
21476        synchronized (mPackages) {
21477            // Verify that all of the preferred activity components actually
21478            // exist.  It is possible for applications to be updated and at
21479            // that point remove a previously declared activity component that
21480            // had been set as a preferred activity.  We try to clean this up
21481            // the next time we encounter that preferred activity, but it is
21482            // possible for the user flow to never be able to return to that
21483            // situation so here we do a sanity check to make sure we haven't
21484            // left any junk around.
21485            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
21486            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21487                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21488                removed.clear();
21489                for (PreferredActivity pa : pir.filterSet()) {
21490                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
21491                        removed.add(pa);
21492                    }
21493                }
21494                if (removed.size() > 0) {
21495                    for (int r=0; r<removed.size(); r++) {
21496                        PreferredActivity pa = removed.get(r);
21497                        Slog.w(TAG, "Removing dangling preferred activity: "
21498                                + pa.mPref.mComponent);
21499                        pir.removeFilter(pa);
21500                    }
21501                    mSettings.writePackageRestrictionsLPr(
21502                            mSettings.mPreferredActivities.keyAt(i));
21503                }
21504            }
21505
21506            for (int userId : UserManagerService.getInstance().getUserIds()) {
21507                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
21508                    grantPermissionsUserIds = ArrayUtils.appendInt(
21509                            grantPermissionsUserIds, userId);
21510                }
21511            }
21512        }
21513        sUserManager.systemReady();
21514
21515        // If we upgraded grant all default permissions before kicking off.
21516        for (int userId : grantPermissionsUserIds) {
21517            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
21518        }
21519
21520        // If we did not grant default permissions, we preload from this the
21521        // default permission exceptions lazily to ensure we don't hit the
21522        // disk on a new user creation.
21523        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
21524            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
21525        }
21526
21527        // Kick off any messages waiting for system ready
21528        if (mPostSystemReadyMessages != null) {
21529            for (Message msg : mPostSystemReadyMessages) {
21530                msg.sendToTarget();
21531            }
21532            mPostSystemReadyMessages = null;
21533        }
21534
21535        // Watch for external volumes that come and go over time
21536        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21537        storage.registerListener(mStorageListener);
21538
21539        mInstallerService.systemReady();
21540        mPackageDexOptimizer.systemReady();
21541
21542        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
21543                StorageManagerInternal.class);
21544        StorageManagerInternal.addExternalStoragePolicy(
21545                new StorageManagerInternal.ExternalStorageMountPolicy() {
21546            @Override
21547            public int getMountMode(int uid, String packageName) {
21548                if (Process.isIsolated(uid)) {
21549                    return Zygote.MOUNT_EXTERNAL_NONE;
21550                }
21551                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
21552                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21553                }
21554                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21555                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21556                }
21557                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21558                    return Zygote.MOUNT_EXTERNAL_READ;
21559                }
21560                return Zygote.MOUNT_EXTERNAL_WRITE;
21561            }
21562
21563            @Override
21564            public boolean hasExternalStorage(int uid, String packageName) {
21565                return true;
21566            }
21567        });
21568
21569        // Now that we're mostly running, clean up stale users and apps
21570        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
21571        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
21572
21573        if (mPrivappPermissionsViolations != null) {
21574            Slog.wtf(TAG,"Signature|privileged permissions not in "
21575                    + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
21576            mPrivappPermissionsViolations = null;
21577        }
21578    }
21579
21580    public void waitForAppDataPrepared() {
21581        if (mPrepareAppDataFuture == null) {
21582            return;
21583        }
21584        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
21585        mPrepareAppDataFuture = null;
21586    }
21587
21588    @Override
21589    public boolean isSafeMode() {
21590        // allow instant applications
21591        return mSafeMode;
21592    }
21593
21594    @Override
21595    public boolean hasSystemUidErrors() {
21596        // allow instant applications
21597        return mHasSystemUidErrors;
21598    }
21599
21600    static String arrayToString(int[] array) {
21601        StringBuffer buf = new StringBuffer(128);
21602        buf.append('[');
21603        if (array != null) {
21604            for (int i=0; i<array.length; i++) {
21605                if (i > 0) buf.append(", ");
21606                buf.append(array[i]);
21607            }
21608        }
21609        buf.append(']');
21610        return buf.toString();
21611    }
21612
21613    static class DumpState {
21614        public static final int DUMP_LIBS = 1 << 0;
21615        public static final int DUMP_FEATURES = 1 << 1;
21616        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
21617        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
21618        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
21619        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
21620        public static final int DUMP_PERMISSIONS = 1 << 6;
21621        public static final int DUMP_PACKAGES = 1 << 7;
21622        public static final int DUMP_SHARED_USERS = 1 << 8;
21623        public static final int DUMP_MESSAGES = 1 << 9;
21624        public static final int DUMP_PROVIDERS = 1 << 10;
21625        public static final int DUMP_VERIFIERS = 1 << 11;
21626        public static final int DUMP_PREFERRED = 1 << 12;
21627        public static final int DUMP_PREFERRED_XML = 1 << 13;
21628        public static final int DUMP_KEYSETS = 1 << 14;
21629        public static final int DUMP_VERSION = 1 << 15;
21630        public static final int DUMP_INSTALLS = 1 << 16;
21631        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
21632        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
21633        public static final int DUMP_FROZEN = 1 << 19;
21634        public static final int DUMP_DEXOPT = 1 << 20;
21635        public static final int DUMP_COMPILER_STATS = 1 << 21;
21636        public static final int DUMP_CHANGES = 1 << 22;
21637
21638        public static final int OPTION_SHOW_FILTERS = 1 << 0;
21639
21640        private int mTypes;
21641
21642        private int mOptions;
21643
21644        private boolean mTitlePrinted;
21645
21646        private SharedUserSetting mSharedUser;
21647
21648        public boolean isDumping(int type) {
21649            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
21650                return true;
21651            }
21652
21653            return (mTypes & type) != 0;
21654        }
21655
21656        public void setDump(int type) {
21657            mTypes |= type;
21658        }
21659
21660        public boolean isOptionEnabled(int option) {
21661            return (mOptions & option) != 0;
21662        }
21663
21664        public void setOptionEnabled(int option) {
21665            mOptions |= option;
21666        }
21667
21668        public boolean onTitlePrinted() {
21669            final boolean printed = mTitlePrinted;
21670            mTitlePrinted = true;
21671            return printed;
21672        }
21673
21674        public boolean getTitlePrinted() {
21675            return mTitlePrinted;
21676        }
21677
21678        public void setTitlePrinted(boolean enabled) {
21679            mTitlePrinted = enabled;
21680        }
21681
21682        public SharedUserSetting getSharedUser() {
21683            return mSharedUser;
21684        }
21685
21686        public void setSharedUser(SharedUserSetting user) {
21687            mSharedUser = user;
21688        }
21689    }
21690
21691    @Override
21692    public void onShellCommand(FileDescriptor in, FileDescriptor out,
21693            FileDescriptor err, String[] args, ShellCallback callback,
21694            ResultReceiver resultReceiver) {
21695        (new PackageManagerShellCommand(this)).exec(
21696                this, in, out, err, args, callback, resultReceiver);
21697    }
21698
21699    @Override
21700    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
21701        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
21702
21703        DumpState dumpState = new DumpState();
21704        boolean fullPreferred = false;
21705        boolean checkin = false;
21706
21707        String packageName = null;
21708        ArraySet<String> permissionNames = null;
21709
21710        int opti = 0;
21711        while (opti < args.length) {
21712            String opt = args[opti];
21713            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
21714                break;
21715            }
21716            opti++;
21717
21718            if ("-a".equals(opt)) {
21719                // Right now we only know how to print all.
21720            } else if ("-h".equals(opt)) {
21721                pw.println("Package manager dump options:");
21722                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
21723                pw.println("    --checkin: dump for a checkin");
21724                pw.println("    -f: print details of intent filters");
21725                pw.println("    -h: print this help");
21726                pw.println("  cmd may be one of:");
21727                pw.println("    l[ibraries]: list known shared libraries");
21728                pw.println("    f[eatures]: list device features");
21729                pw.println("    k[eysets]: print known keysets");
21730                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
21731                pw.println("    perm[issions]: dump permissions");
21732                pw.println("    permission [name ...]: dump declaration and use of given permission");
21733                pw.println("    pref[erred]: print preferred package settings");
21734                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
21735                pw.println("    prov[iders]: dump content providers");
21736                pw.println("    p[ackages]: dump installed packages");
21737                pw.println("    s[hared-users]: dump shared user IDs");
21738                pw.println("    m[essages]: print collected runtime messages");
21739                pw.println("    v[erifiers]: print package verifier info");
21740                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
21741                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
21742                pw.println("    version: print database version info");
21743                pw.println("    write: write current settings now");
21744                pw.println("    installs: details about install sessions");
21745                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
21746                pw.println("    dexopt: dump dexopt state");
21747                pw.println("    compiler-stats: dump compiler statistics");
21748                pw.println("    enabled-overlays: dump list of enabled overlay packages");
21749                pw.println("    <package.name>: info about given package");
21750                return;
21751            } else if ("--checkin".equals(opt)) {
21752                checkin = true;
21753            } else if ("-f".equals(opt)) {
21754                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21755            } else if ("--proto".equals(opt)) {
21756                dumpProto(fd);
21757                return;
21758            } else {
21759                pw.println("Unknown argument: " + opt + "; use -h for help");
21760            }
21761        }
21762
21763        // Is the caller requesting to dump a particular piece of data?
21764        if (opti < args.length) {
21765            String cmd = args[opti];
21766            opti++;
21767            // Is this a package name?
21768            if ("android".equals(cmd) || cmd.contains(".")) {
21769                packageName = cmd;
21770                // When dumping a single package, we always dump all of its
21771                // filter information since the amount of data will be reasonable.
21772                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21773            } else if ("check-permission".equals(cmd)) {
21774                if (opti >= args.length) {
21775                    pw.println("Error: check-permission missing permission argument");
21776                    return;
21777                }
21778                String perm = args[opti];
21779                opti++;
21780                if (opti >= args.length) {
21781                    pw.println("Error: check-permission missing package argument");
21782                    return;
21783                }
21784
21785                String pkg = args[opti];
21786                opti++;
21787                int user = UserHandle.getUserId(Binder.getCallingUid());
21788                if (opti < args.length) {
21789                    try {
21790                        user = Integer.parseInt(args[opti]);
21791                    } catch (NumberFormatException e) {
21792                        pw.println("Error: check-permission user argument is not a number: "
21793                                + args[opti]);
21794                        return;
21795                    }
21796                }
21797
21798                // Normalize package name to handle renamed packages and static libs
21799                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
21800
21801                pw.println(checkPermission(perm, pkg, user));
21802                return;
21803            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
21804                dumpState.setDump(DumpState.DUMP_LIBS);
21805            } else if ("f".equals(cmd) || "features".equals(cmd)) {
21806                dumpState.setDump(DumpState.DUMP_FEATURES);
21807            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
21808                if (opti >= args.length) {
21809                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
21810                            | DumpState.DUMP_SERVICE_RESOLVERS
21811                            | DumpState.DUMP_RECEIVER_RESOLVERS
21812                            | DumpState.DUMP_CONTENT_RESOLVERS);
21813                } else {
21814                    while (opti < args.length) {
21815                        String name = args[opti];
21816                        if ("a".equals(name) || "activity".equals(name)) {
21817                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
21818                        } else if ("s".equals(name) || "service".equals(name)) {
21819                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
21820                        } else if ("r".equals(name) || "receiver".equals(name)) {
21821                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
21822                        } else if ("c".equals(name) || "content".equals(name)) {
21823                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
21824                        } else {
21825                            pw.println("Error: unknown resolver table type: " + name);
21826                            return;
21827                        }
21828                        opti++;
21829                    }
21830                }
21831            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
21832                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
21833            } else if ("permission".equals(cmd)) {
21834                if (opti >= args.length) {
21835                    pw.println("Error: permission requires permission name");
21836                    return;
21837                }
21838                permissionNames = new ArraySet<>();
21839                while (opti < args.length) {
21840                    permissionNames.add(args[opti]);
21841                    opti++;
21842                }
21843                dumpState.setDump(DumpState.DUMP_PERMISSIONS
21844                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
21845            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
21846                dumpState.setDump(DumpState.DUMP_PREFERRED);
21847            } else if ("preferred-xml".equals(cmd)) {
21848                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
21849                if (opti < args.length && "--full".equals(args[opti])) {
21850                    fullPreferred = true;
21851                    opti++;
21852                }
21853            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
21854                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
21855            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
21856                dumpState.setDump(DumpState.DUMP_PACKAGES);
21857            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
21858                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
21859            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
21860                dumpState.setDump(DumpState.DUMP_PROVIDERS);
21861            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
21862                dumpState.setDump(DumpState.DUMP_MESSAGES);
21863            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
21864                dumpState.setDump(DumpState.DUMP_VERIFIERS);
21865            } else if ("i".equals(cmd) || "ifv".equals(cmd)
21866                    || "intent-filter-verifiers".equals(cmd)) {
21867                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
21868            } else if ("version".equals(cmd)) {
21869                dumpState.setDump(DumpState.DUMP_VERSION);
21870            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
21871                dumpState.setDump(DumpState.DUMP_KEYSETS);
21872            } else if ("installs".equals(cmd)) {
21873                dumpState.setDump(DumpState.DUMP_INSTALLS);
21874            } else if ("frozen".equals(cmd)) {
21875                dumpState.setDump(DumpState.DUMP_FROZEN);
21876            } else if ("dexopt".equals(cmd)) {
21877                dumpState.setDump(DumpState.DUMP_DEXOPT);
21878            } else if ("compiler-stats".equals(cmd)) {
21879                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
21880            } else if ("changes".equals(cmd)) {
21881                dumpState.setDump(DumpState.DUMP_CHANGES);
21882            } else if ("write".equals(cmd)) {
21883                synchronized (mPackages) {
21884                    mSettings.writeLPr();
21885                    pw.println("Settings written.");
21886                    return;
21887                }
21888            }
21889        }
21890
21891        if (checkin) {
21892            pw.println("vers,1");
21893        }
21894
21895        // reader
21896        synchronized (mPackages) {
21897            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
21898                if (!checkin) {
21899                    if (dumpState.onTitlePrinted())
21900                        pw.println();
21901                    pw.println("Database versions:");
21902                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
21903                }
21904            }
21905
21906            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
21907                if (!checkin) {
21908                    if (dumpState.onTitlePrinted())
21909                        pw.println();
21910                    pw.println("Verifiers:");
21911                    pw.print("  Required: ");
21912                    pw.print(mRequiredVerifierPackage);
21913                    pw.print(" (uid=");
21914                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21915                            UserHandle.USER_SYSTEM));
21916                    pw.println(")");
21917                } else if (mRequiredVerifierPackage != null) {
21918                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
21919                    pw.print(",");
21920                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21921                            UserHandle.USER_SYSTEM));
21922                }
21923            }
21924
21925            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
21926                    packageName == null) {
21927                if (mIntentFilterVerifierComponent != null) {
21928                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21929                    if (!checkin) {
21930                        if (dumpState.onTitlePrinted())
21931                            pw.println();
21932                        pw.println("Intent Filter Verifier:");
21933                        pw.print("  Using: ");
21934                        pw.print(verifierPackageName);
21935                        pw.print(" (uid=");
21936                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21937                                UserHandle.USER_SYSTEM));
21938                        pw.println(")");
21939                    } else if (verifierPackageName != null) {
21940                        pw.print("ifv,"); pw.print(verifierPackageName);
21941                        pw.print(",");
21942                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21943                                UserHandle.USER_SYSTEM));
21944                    }
21945                } else {
21946                    pw.println();
21947                    pw.println("No Intent Filter Verifier available!");
21948                }
21949            }
21950
21951            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
21952                boolean printedHeader = false;
21953                final Iterator<String> it = mSharedLibraries.keySet().iterator();
21954                while (it.hasNext()) {
21955                    String libName = it.next();
21956                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
21957                    if (versionedLib == null) {
21958                        continue;
21959                    }
21960                    final int versionCount = versionedLib.size();
21961                    for (int i = 0; i < versionCount; i++) {
21962                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
21963                        if (!checkin) {
21964                            if (!printedHeader) {
21965                                if (dumpState.onTitlePrinted())
21966                                    pw.println();
21967                                pw.println("Libraries:");
21968                                printedHeader = true;
21969                            }
21970                            pw.print("  ");
21971                        } else {
21972                            pw.print("lib,");
21973                        }
21974                        pw.print(libEntry.info.getName());
21975                        if (libEntry.info.isStatic()) {
21976                            pw.print(" version=" + libEntry.info.getVersion());
21977                        }
21978                        if (!checkin) {
21979                            pw.print(" -> ");
21980                        }
21981                        if (libEntry.path != null) {
21982                            pw.print(" (jar) ");
21983                            pw.print(libEntry.path);
21984                        } else {
21985                            pw.print(" (apk) ");
21986                            pw.print(libEntry.apk);
21987                        }
21988                        pw.println();
21989                    }
21990                }
21991            }
21992
21993            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
21994                if (dumpState.onTitlePrinted())
21995                    pw.println();
21996                if (!checkin) {
21997                    pw.println("Features:");
21998                }
21999
22000                synchronized (mAvailableFeatures) {
22001                    for (FeatureInfo feat : mAvailableFeatures.values()) {
22002                        if (checkin) {
22003                            pw.print("feat,");
22004                            pw.print(feat.name);
22005                            pw.print(",");
22006                            pw.println(feat.version);
22007                        } else {
22008                            pw.print("  ");
22009                            pw.print(feat.name);
22010                            if (feat.version > 0) {
22011                                pw.print(" version=");
22012                                pw.print(feat.version);
22013                            }
22014                            pw.println();
22015                        }
22016                    }
22017                }
22018            }
22019
22020            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
22021                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
22022                        : "Activity Resolver Table:", "  ", packageName,
22023                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22024                    dumpState.setTitlePrinted(true);
22025                }
22026            }
22027            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
22028                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
22029                        : "Receiver Resolver Table:", "  ", packageName,
22030                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22031                    dumpState.setTitlePrinted(true);
22032                }
22033            }
22034            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
22035                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
22036                        : "Service Resolver Table:", "  ", packageName,
22037                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22038                    dumpState.setTitlePrinted(true);
22039                }
22040            }
22041            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
22042                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
22043                        : "Provider Resolver Table:", "  ", packageName,
22044                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22045                    dumpState.setTitlePrinted(true);
22046                }
22047            }
22048
22049            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
22050                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
22051                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
22052                    int user = mSettings.mPreferredActivities.keyAt(i);
22053                    if (pir.dump(pw,
22054                            dumpState.getTitlePrinted()
22055                                ? "\nPreferred Activities User " + user + ":"
22056                                : "Preferred Activities User " + user + ":", "  ",
22057                            packageName, true, false)) {
22058                        dumpState.setTitlePrinted(true);
22059                    }
22060                }
22061            }
22062
22063            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
22064                pw.flush();
22065                FileOutputStream fout = new FileOutputStream(fd);
22066                BufferedOutputStream str = new BufferedOutputStream(fout);
22067                XmlSerializer serializer = new FastXmlSerializer();
22068                try {
22069                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
22070                    serializer.startDocument(null, true);
22071                    serializer.setFeature(
22072                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
22073                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
22074                    serializer.endDocument();
22075                    serializer.flush();
22076                } catch (IllegalArgumentException e) {
22077                    pw.println("Failed writing: " + e);
22078                } catch (IllegalStateException e) {
22079                    pw.println("Failed writing: " + e);
22080                } catch (IOException e) {
22081                    pw.println("Failed writing: " + e);
22082                }
22083            }
22084
22085            if (!checkin
22086                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
22087                    && packageName == null) {
22088                pw.println();
22089                int count = mSettings.mPackages.size();
22090                if (count == 0) {
22091                    pw.println("No applications!");
22092                    pw.println();
22093                } else {
22094                    final String prefix = "  ";
22095                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
22096                    if (allPackageSettings.size() == 0) {
22097                        pw.println("No domain preferred apps!");
22098                        pw.println();
22099                    } else {
22100                        pw.println("App verification status:");
22101                        pw.println();
22102                        count = 0;
22103                        for (PackageSetting ps : allPackageSettings) {
22104                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
22105                            if (ivi == null || ivi.getPackageName() == null) continue;
22106                            pw.println(prefix + "Package: " + ivi.getPackageName());
22107                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
22108                            pw.println(prefix + "Status:  " + ivi.getStatusString());
22109                            pw.println();
22110                            count++;
22111                        }
22112                        if (count == 0) {
22113                            pw.println(prefix + "No app verification established.");
22114                            pw.println();
22115                        }
22116                        for (int userId : sUserManager.getUserIds()) {
22117                            pw.println("App linkages for user " + userId + ":");
22118                            pw.println();
22119                            count = 0;
22120                            for (PackageSetting ps : allPackageSettings) {
22121                                final long status = ps.getDomainVerificationStatusForUser(userId);
22122                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
22123                                        && !DEBUG_DOMAIN_VERIFICATION) {
22124                                    continue;
22125                                }
22126                                pw.println(prefix + "Package: " + ps.name);
22127                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
22128                                String statusStr = IntentFilterVerificationInfo.
22129                                        getStatusStringFromValue(status);
22130                                pw.println(prefix + "Status:  " + statusStr);
22131                                pw.println();
22132                                count++;
22133                            }
22134                            if (count == 0) {
22135                                pw.println(prefix + "No configured app linkages.");
22136                                pw.println();
22137                            }
22138                        }
22139                    }
22140                }
22141            }
22142
22143            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
22144                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
22145                if (packageName == null && permissionNames == null) {
22146                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
22147                        if (iperm == 0) {
22148                            if (dumpState.onTitlePrinted())
22149                                pw.println();
22150                            pw.println("AppOp Permissions:");
22151                        }
22152                        pw.print("  AppOp Permission ");
22153                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
22154                        pw.println(":");
22155                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
22156                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
22157                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
22158                        }
22159                    }
22160                }
22161            }
22162
22163            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
22164                boolean printedSomething = false;
22165                for (PackageParser.Provider p : mProviders.mProviders.values()) {
22166                    if (packageName != null && !packageName.equals(p.info.packageName)) {
22167                        continue;
22168                    }
22169                    if (!printedSomething) {
22170                        if (dumpState.onTitlePrinted())
22171                            pw.println();
22172                        pw.println("Registered ContentProviders:");
22173                        printedSomething = true;
22174                    }
22175                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
22176                    pw.print("    "); pw.println(p.toString());
22177                }
22178                printedSomething = false;
22179                for (Map.Entry<String, PackageParser.Provider> entry :
22180                        mProvidersByAuthority.entrySet()) {
22181                    PackageParser.Provider p = entry.getValue();
22182                    if (packageName != null && !packageName.equals(p.info.packageName)) {
22183                        continue;
22184                    }
22185                    if (!printedSomething) {
22186                        if (dumpState.onTitlePrinted())
22187                            pw.println();
22188                        pw.println("ContentProvider Authorities:");
22189                        printedSomething = true;
22190                    }
22191                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
22192                    pw.print("    "); pw.println(p.toString());
22193                    if (p.info != null && p.info.applicationInfo != null) {
22194                        final String appInfo = p.info.applicationInfo.toString();
22195                        pw.print("      applicationInfo="); pw.println(appInfo);
22196                    }
22197                }
22198            }
22199
22200            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
22201                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
22202            }
22203
22204            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
22205                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
22206            }
22207
22208            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
22209                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
22210            }
22211
22212            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
22213                if (dumpState.onTitlePrinted()) pw.println();
22214                pw.println("Package Changes:");
22215                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
22216                final int K = mChangedPackages.size();
22217                for (int i = 0; i < K; i++) {
22218                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
22219                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
22220                    final int N = changes.size();
22221                    if (N == 0) {
22222                        pw.print("    "); pw.println("No packages changed");
22223                    } else {
22224                        for (int j = 0; j < N; j++) {
22225                            final String pkgName = changes.valueAt(j);
22226                            final int sequenceNumber = changes.keyAt(j);
22227                            pw.print("    ");
22228                            pw.print("seq=");
22229                            pw.print(sequenceNumber);
22230                            pw.print(", package=");
22231                            pw.println(pkgName);
22232                        }
22233                    }
22234                }
22235            }
22236
22237            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
22238                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
22239            }
22240
22241            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
22242                // XXX should handle packageName != null by dumping only install data that
22243                // the given package is involved with.
22244                if (dumpState.onTitlePrinted()) pw.println();
22245
22246                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22247                ipw.println();
22248                ipw.println("Frozen packages:");
22249                ipw.increaseIndent();
22250                if (mFrozenPackages.size() == 0) {
22251                    ipw.println("(none)");
22252                } else {
22253                    for (int i = 0; i < mFrozenPackages.size(); i++) {
22254                        ipw.println(mFrozenPackages.valueAt(i));
22255                    }
22256                }
22257                ipw.decreaseIndent();
22258            }
22259
22260            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
22261                if (dumpState.onTitlePrinted()) pw.println();
22262                dumpDexoptStateLPr(pw, packageName);
22263            }
22264
22265            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
22266                if (dumpState.onTitlePrinted()) pw.println();
22267                dumpCompilerStatsLPr(pw, packageName);
22268            }
22269
22270            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
22271                if (dumpState.onTitlePrinted()) pw.println();
22272                mSettings.dumpReadMessagesLPr(pw, dumpState);
22273
22274                pw.println();
22275                pw.println("Package warning messages:");
22276                BufferedReader in = null;
22277                String line = null;
22278                try {
22279                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22280                    while ((line = in.readLine()) != null) {
22281                        if (line.contains("ignored: updated version")) continue;
22282                        pw.println(line);
22283                    }
22284                } catch (IOException ignored) {
22285                } finally {
22286                    IoUtils.closeQuietly(in);
22287                }
22288            }
22289
22290            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
22291                BufferedReader in = null;
22292                String line = null;
22293                try {
22294                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22295                    while ((line = in.readLine()) != null) {
22296                        if (line.contains("ignored: updated version")) continue;
22297                        pw.print("msg,");
22298                        pw.println(line);
22299                    }
22300                } catch (IOException ignored) {
22301                } finally {
22302                    IoUtils.closeQuietly(in);
22303                }
22304            }
22305        }
22306
22307        // PackageInstaller should be called outside of mPackages lock
22308        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
22309            // XXX should handle packageName != null by dumping only install data that
22310            // the given package is involved with.
22311            if (dumpState.onTitlePrinted()) pw.println();
22312            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
22313        }
22314    }
22315
22316    private void dumpProto(FileDescriptor fd) {
22317        final ProtoOutputStream proto = new ProtoOutputStream(fd);
22318
22319        synchronized (mPackages) {
22320            final long requiredVerifierPackageToken =
22321                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
22322            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
22323            proto.write(
22324                    PackageServiceDumpProto.PackageShortProto.UID,
22325                    getPackageUid(
22326                            mRequiredVerifierPackage,
22327                            MATCH_DEBUG_TRIAGED_MISSING,
22328                            UserHandle.USER_SYSTEM));
22329            proto.end(requiredVerifierPackageToken);
22330
22331            if (mIntentFilterVerifierComponent != null) {
22332                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
22333                final long verifierPackageToken =
22334                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
22335                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
22336                proto.write(
22337                        PackageServiceDumpProto.PackageShortProto.UID,
22338                        getPackageUid(
22339                                verifierPackageName,
22340                                MATCH_DEBUG_TRIAGED_MISSING,
22341                                UserHandle.USER_SYSTEM));
22342                proto.end(verifierPackageToken);
22343            }
22344
22345            dumpSharedLibrariesProto(proto);
22346            dumpFeaturesProto(proto);
22347            mSettings.dumpPackagesProto(proto);
22348            mSettings.dumpSharedUsersProto(proto);
22349            dumpMessagesProto(proto);
22350        }
22351        proto.flush();
22352    }
22353
22354    private void dumpMessagesProto(ProtoOutputStream proto) {
22355        BufferedReader in = null;
22356        String line = null;
22357        try {
22358            in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22359            while ((line = in.readLine()) != null) {
22360                if (line.contains("ignored: updated version")) continue;
22361                proto.write(PackageServiceDumpProto.MESSAGES, line);
22362            }
22363        } catch (IOException ignored) {
22364        } finally {
22365            IoUtils.closeQuietly(in);
22366        }
22367    }
22368
22369    private void dumpFeaturesProto(ProtoOutputStream proto) {
22370        synchronized (mAvailableFeatures) {
22371            final int count = mAvailableFeatures.size();
22372            for (int i = 0; i < count; i++) {
22373                final FeatureInfo feat = mAvailableFeatures.valueAt(i);
22374                final long featureToken = proto.start(PackageServiceDumpProto.FEATURES);
22375                proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name);
22376                proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version);
22377                proto.end(featureToken);
22378            }
22379        }
22380    }
22381
22382    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
22383        final int count = mSharedLibraries.size();
22384        for (int i = 0; i < count; i++) {
22385            final String libName = mSharedLibraries.keyAt(i);
22386            SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
22387            if (versionedLib == null) {
22388                continue;
22389            }
22390            final int versionCount = versionedLib.size();
22391            for (int j = 0; j < versionCount; j++) {
22392                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
22393                final long sharedLibraryToken =
22394                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
22395                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
22396                final boolean isJar = (libEntry.path != null);
22397                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
22398                if (isJar) {
22399                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
22400                } else {
22401                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
22402                }
22403                proto.end(sharedLibraryToken);
22404            }
22405        }
22406    }
22407
22408    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
22409        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22410        ipw.println();
22411        ipw.println("Dexopt state:");
22412        ipw.increaseIndent();
22413        Collection<PackageParser.Package> packages = null;
22414        if (packageName != null) {
22415            PackageParser.Package targetPackage = mPackages.get(packageName);
22416            if (targetPackage != null) {
22417                packages = Collections.singletonList(targetPackage);
22418            } else {
22419                ipw.println("Unable to find package: " + packageName);
22420                return;
22421            }
22422        } else {
22423            packages = mPackages.values();
22424        }
22425
22426        for (PackageParser.Package pkg : packages) {
22427            ipw.println("[" + pkg.packageName + "]");
22428            ipw.increaseIndent();
22429            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
22430            ipw.decreaseIndent();
22431        }
22432    }
22433
22434    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
22435        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22436        ipw.println();
22437        ipw.println("Compiler stats:");
22438        ipw.increaseIndent();
22439        Collection<PackageParser.Package> packages = null;
22440        if (packageName != null) {
22441            PackageParser.Package targetPackage = mPackages.get(packageName);
22442            if (targetPackage != null) {
22443                packages = Collections.singletonList(targetPackage);
22444            } else {
22445                ipw.println("Unable to find package: " + packageName);
22446                return;
22447            }
22448        } else {
22449            packages = mPackages.values();
22450        }
22451
22452        for (PackageParser.Package pkg : packages) {
22453            ipw.println("[" + pkg.packageName + "]");
22454            ipw.increaseIndent();
22455
22456            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
22457            if (stats == null) {
22458                ipw.println("(No recorded stats)");
22459            } else {
22460                stats.dump(ipw);
22461            }
22462            ipw.decreaseIndent();
22463        }
22464    }
22465
22466    private String dumpDomainString(String packageName) {
22467        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
22468                .getList();
22469        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
22470
22471        ArraySet<String> result = new ArraySet<>();
22472        if (iviList.size() > 0) {
22473            for (IntentFilterVerificationInfo ivi : iviList) {
22474                for (String host : ivi.getDomains()) {
22475                    result.add(host);
22476                }
22477            }
22478        }
22479        if (filters != null && filters.size() > 0) {
22480            for (IntentFilter filter : filters) {
22481                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
22482                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
22483                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
22484                    result.addAll(filter.getHostsList());
22485                }
22486            }
22487        }
22488
22489        StringBuilder sb = new StringBuilder(result.size() * 16);
22490        for (String domain : result) {
22491            if (sb.length() > 0) sb.append(" ");
22492            sb.append(domain);
22493        }
22494        return sb.toString();
22495    }
22496
22497    // ------- apps on sdcard specific code -------
22498    static final boolean DEBUG_SD_INSTALL = false;
22499
22500    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
22501
22502    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
22503
22504    private boolean mMediaMounted = false;
22505
22506    static String getEncryptKey() {
22507        try {
22508            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
22509                    SD_ENCRYPTION_KEYSTORE_NAME);
22510            if (sdEncKey == null) {
22511                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
22512                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
22513                if (sdEncKey == null) {
22514                    Slog.e(TAG, "Failed to create encryption keys");
22515                    return null;
22516                }
22517            }
22518            return sdEncKey;
22519        } catch (NoSuchAlgorithmException nsae) {
22520            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
22521            return null;
22522        } catch (IOException ioe) {
22523            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
22524            return null;
22525        }
22526    }
22527
22528    /*
22529     * Update media status on PackageManager.
22530     */
22531    @Override
22532    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
22533        enforceSystemOrRoot("Media status can only be updated by the system");
22534        // reader; this apparently protects mMediaMounted, but should probably
22535        // be a different lock in that case.
22536        synchronized (mPackages) {
22537            Log.i(TAG, "Updating external media status from "
22538                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
22539                    + (mediaStatus ? "mounted" : "unmounted"));
22540            if (DEBUG_SD_INSTALL)
22541                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
22542                        + ", mMediaMounted=" + mMediaMounted);
22543            if (mediaStatus == mMediaMounted) {
22544                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
22545                        : 0, -1);
22546                mHandler.sendMessage(msg);
22547                return;
22548            }
22549            mMediaMounted = mediaStatus;
22550        }
22551        // Queue up an async operation since the package installation may take a
22552        // little while.
22553        mHandler.post(new Runnable() {
22554            public void run() {
22555                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
22556            }
22557        });
22558    }
22559
22560    /**
22561     * Called by StorageManagerService when the initial ASECs to scan are available.
22562     * Should block until all the ASEC containers are finished being scanned.
22563     */
22564    public void scanAvailableAsecs() {
22565        updateExternalMediaStatusInner(true, false, false);
22566    }
22567
22568    /*
22569     * Collect information of applications on external media, map them against
22570     * existing containers and update information based on current mount status.
22571     * Please note that we always have to report status if reportStatus has been
22572     * set to true especially when unloading packages.
22573     */
22574    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
22575            boolean externalStorage) {
22576        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
22577        int[] uidArr = EmptyArray.INT;
22578
22579        final String[] list = PackageHelper.getSecureContainerList();
22580        if (ArrayUtils.isEmpty(list)) {
22581            Log.i(TAG, "No secure containers found");
22582        } else {
22583            // Process list of secure containers and categorize them
22584            // as active or stale based on their package internal state.
22585
22586            // reader
22587            synchronized (mPackages) {
22588                for (String cid : list) {
22589                    // Leave stages untouched for now; installer service owns them
22590                    if (PackageInstallerService.isStageName(cid)) continue;
22591
22592                    if (DEBUG_SD_INSTALL)
22593                        Log.i(TAG, "Processing container " + cid);
22594                    String pkgName = getAsecPackageName(cid);
22595                    if (pkgName == null) {
22596                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
22597                        continue;
22598                    }
22599                    if (DEBUG_SD_INSTALL)
22600                        Log.i(TAG, "Looking for pkg : " + pkgName);
22601
22602                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
22603                    if (ps == null) {
22604                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
22605                        continue;
22606                    }
22607
22608                    /*
22609                     * Skip packages that are not external if we're unmounting
22610                     * external storage.
22611                     */
22612                    if (externalStorage && !isMounted && !isExternal(ps)) {
22613                        continue;
22614                    }
22615
22616                    final AsecInstallArgs args = new AsecInstallArgs(cid,
22617                            getAppDexInstructionSets(ps), ps.isForwardLocked());
22618                    // The package status is changed only if the code path
22619                    // matches between settings and the container id.
22620                    if (ps.codePathString != null
22621                            && ps.codePathString.startsWith(args.getCodePath())) {
22622                        if (DEBUG_SD_INSTALL) {
22623                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
22624                                    + " at code path: " + ps.codePathString);
22625                        }
22626
22627                        // We do have a valid package installed on sdcard
22628                        processCids.put(args, ps.codePathString);
22629                        final int uid = ps.appId;
22630                        if (uid != -1) {
22631                            uidArr = ArrayUtils.appendInt(uidArr, uid);
22632                        }
22633                    } else {
22634                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
22635                                + ps.codePathString);
22636                    }
22637                }
22638            }
22639
22640            Arrays.sort(uidArr);
22641        }
22642
22643        // Process packages with valid entries.
22644        if (isMounted) {
22645            if (DEBUG_SD_INSTALL)
22646                Log.i(TAG, "Loading packages");
22647            loadMediaPackages(processCids, uidArr, externalStorage);
22648            startCleaningPackages();
22649            mInstallerService.onSecureContainersAvailable();
22650        } else {
22651            if (DEBUG_SD_INSTALL)
22652                Log.i(TAG, "Unloading packages");
22653            unloadMediaPackages(processCids, uidArr, reportStatus);
22654        }
22655    }
22656
22657    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22658            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
22659        final int size = infos.size();
22660        final String[] packageNames = new String[size];
22661        final int[] packageUids = new int[size];
22662        for (int i = 0; i < size; i++) {
22663            final ApplicationInfo info = infos.get(i);
22664            packageNames[i] = info.packageName;
22665            packageUids[i] = info.uid;
22666        }
22667        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
22668                finishedReceiver);
22669    }
22670
22671    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22672            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
22673        sendResourcesChangedBroadcast(mediaStatus, replacing,
22674                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
22675    }
22676
22677    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22678            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
22679        int size = pkgList.length;
22680        if (size > 0) {
22681            // Send broadcasts here
22682            Bundle extras = new Bundle();
22683            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
22684            if (uidArr != null) {
22685                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
22686            }
22687            if (replacing) {
22688                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
22689            }
22690            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
22691                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
22692            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
22693        }
22694    }
22695
22696   /*
22697     * Look at potentially valid container ids from processCids If package
22698     * information doesn't match the one on record or package scanning fails,
22699     * the cid is added to list of removeCids. We currently don't delete stale
22700     * containers.
22701     */
22702    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
22703            boolean externalStorage) {
22704        ArrayList<String> pkgList = new ArrayList<String>();
22705        Set<AsecInstallArgs> keys = processCids.keySet();
22706
22707        for (AsecInstallArgs args : keys) {
22708            String codePath = processCids.get(args);
22709            if (DEBUG_SD_INSTALL)
22710                Log.i(TAG, "Loading container : " + args.cid);
22711            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
22712            try {
22713                // Make sure there are no container errors first.
22714                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
22715                    Slog.e(TAG, "Failed to mount cid : " + args.cid
22716                            + " when installing from sdcard");
22717                    continue;
22718                }
22719                // Check code path here.
22720                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
22721                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
22722                            + " does not match one in settings " + codePath);
22723                    continue;
22724                }
22725                // Parse package
22726                int parseFlags = mDefParseFlags;
22727                if (args.isExternalAsec()) {
22728                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
22729                }
22730                if (args.isFwdLocked()) {
22731                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
22732                }
22733
22734                synchronized (mInstallLock) {
22735                    PackageParser.Package pkg = null;
22736                    try {
22737                        // Sadly we don't know the package name yet to freeze it
22738                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
22739                                SCAN_IGNORE_FROZEN, 0, null);
22740                    } catch (PackageManagerException e) {
22741                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
22742                    }
22743                    // Scan the package
22744                    if (pkg != null) {
22745                        /*
22746                         * TODO why is the lock being held? doPostInstall is
22747                         * called in other places without the lock. This needs
22748                         * to be straightened out.
22749                         */
22750                        // writer
22751                        synchronized (mPackages) {
22752                            retCode = PackageManager.INSTALL_SUCCEEDED;
22753                            pkgList.add(pkg.packageName);
22754                            // Post process args
22755                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
22756                                    pkg.applicationInfo.uid);
22757                        }
22758                    } else {
22759                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
22760                    }
22761                }
22762
22763            } finally {
22764                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
22765                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
22766                }
22767            }
22768        }
22769        // writer
22770        synchronized (mPackages) {
22771            // If the platform SDK has changed since the last time we booted,
22772            // we need to re-grant app permission to catch any new ones that
22773            // appear. This is really a hack, and means that apps can in some
22774            // cases get permissions that the user didn't initially explicitly
22775            // allow... it would be nice to have some better way to handle
22776            // this situation.
22777            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
22778                    : mSettings.getInternalVersion();
22779            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
22780                    : StorageManager.UUID_PRIVATE_INTERNAL;
22781
22782            int updateFlags = UPDATE_PERMISSIONS_ALL;
22783            if (ver.sdkVersion != mSdkVersion) {
22784                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
22785                        + mSdkVersion + "; regranting permissions for external");
22786                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
22787            }
22788            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
22789
22790            // Yay, everything is now upgraded
22791            ver.forceCurrent();
22792
22793            // can downgrade to reader
22794            // Persist settings
22795            mSettings.writeLPr();
22796        }
22797        // Send a broadcast to let everyone know we are done processing
22798        if (pkgList.size() > 0) {
22799            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
22800        }
22801    }
22802
22803   /*
22804     * Utility method to unload a list of specified containers
22805     */
22806    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
22807        // Just unmount all valid containers.
22808        for (AsecInstallArgs arg : cidArgs) {
22809            synchronized (mInstallLock) {
22810                arg.doPostDeleteLI(false);
22811           }
22812       }
22813   }
22814
22815    /*
22816     * Unload packages mounted on external media. This involves deleting package
22817     * data from internal structures, sending broadcasts about disabled packages,
22818     * gc'ing to free up references, unmounting all secure containers
22819     * corresponding to packages on external media, and posting a
22820     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
22821     * that we always have to post this message if status has been requested no
22822     * matter what.
22823     */
22824    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
22825            final boolean reportStatus) {
22826        if (DEBUG_SD_INSTALL)
22827            Log.i(TAG, "unloading media packages");
22828        ArrayList<String> pkgList = new ArrayList<String>();
22829        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
22830        final Set<AsecInstallArgs> keys = processCids.keySet();
22831        for (AsecInstallArgs args : keys) {
22832            String pkgName = args.getPackageName();
22833            if (DEBUG_SD_INSTALL)
22834                Log.i(TAG, "Trying to unload pkg : " + pkgName);
22835            // Delete package internally
22836            PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
22837            synchronized (mInstallLock) {
22838                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
22839                final boolean res;
22840                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
22841                        "unloadMediaPackages")) {
22842                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
22843                            null);
22844                }
22845                if (res) {
22846                    pkgList.add(pkgName);
22847                } else {
22848                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
22849                    failedList.add(args);
22850                }
22851            }
22852        }
22853
22854        // reader
22855        synchronized (mPackages) {
22856            // We didn't update the settings after removing each package;
22857            // write them now for all packages.
22858            mSettings.writeLPr();
22859        }
22860
22861        // We have to absolutely send UPDATED_MEDIA_STATUS only
22862        // after confirming that all the receivers processed the ordered
22863        // broadcast when packages get disabled, force a gc to clean things up.
22864        // and unload all the containers.
22865        if (pkgList.size() > 0) {
22866            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
22867                    new IIntentReceiver.Stub() {
22868                public void performReceive(Intent intent, int resultCode, String data,
22869                        Bundle extras, boolean ordered, boolean sticky,
22870                        int sendingUser) throws RemoteException {
22871                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
22872                            reportStatus ? 1 : 0, 1, keys);
22873                    mHandler.sendMessage(msg);
22874                }
22875            });
22876        } else {
22877            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
22878                    keys);
22879            mHandler.sendMessage(msg);
22880        }
22881    }
22882
22883    private void loadPrivatePackages(final VolumeInfo vol) {
22884        mHandler.post(new Runnable() {
22885            @Override
22886            public void run() {
22887                loadPrivatePackagesInner(vol);
22888            }
22889        });
22890    }
22891
22892    private void loadPrivatePackagesInner(VolumeInfo vol) {
22893        final String volumeUuid = vol.fsUuid;
22894        if (TextUtils.isEmpty(volumeUuid)) {
22895            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
22896            return;
22897        }
22898
22899        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
22900        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
22901        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
22902
22903        final VersionInfo ver;
22904        final List<PackageSetting> packages;
22905        synchronized (mPackages) {
22906            ver = mSettings.findOrCreateVersion(volumeUuid);
22907            packages = mSettings.getVolumePackagesLPr(volumeUuid);
22908        }
22909
22910        for (PackageSetting ps : packages) {
22911            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
22912            synchronized (mInstallLock) {
22913                final PackageParser.Package pkg;
22914                try {
22915                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
22916                    loaded.add(pkg.applicationInfo);
22917
22918                } catch (PackageManagerException e) {
22919                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
22920                }
22921
22922                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
22923                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
22924                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
22925                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
22926                }
22927            }
22928        }
22929
22930        // Reconcile app data for all started/unlocked users
22931        final StorageManager sm = mContext.getSystemService(StorageManager.class);
22932        final UserManager um = mContext.getSystemService(UserManager.class);
22933        UserManagerInternal umInternal = getUserManagerInternal();
22934        for (UserInfo user : um.getUsers()) {
22935            final int flags;
22936            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
22937                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
22938            } else if (umInternal.isUserRunning(user.id)) {
22939                flags = StorageManager.FLAG_STORAGE_DE;
22940            } else {
22941                continue;
22942            }
22943
22944            try {
22945                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
22946                synchronized (mInstallLock) {
22947                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
22948                }
22949            } catch (IllegalStateException e) {
22950                // Device was probably ejected, and we'll process that event momentarily
22951                Slog.w(TAG, "Failed to prepare storage: " + e);
22952            }
22953        }
22954
22955        synchronized (mPackages) {
22956            int updateFlags = UPDATE_PERMISSIONS_ALL;
22957            if (ver.sdkVersion != mSdkVersion) {
22958                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
22959                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
22960                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
22961            }
22962            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
22963
22964            // Yay, everything is now upgraded
22965            ver.forceCurrent();
22966
22967            mSettings.writeLPr();
22968        }
22969
22970        for (PackageFreezer freezer : freezers) {
22971            freezer.close();
22972        }
22973
22974        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
22975        sendResourcesChangedBroadcast(true, false, loaded, null);
22976    }
22977
22978    private void unloadPrivatePackages(final VolumeInfo vol) {
22979        mHandler.post(new Runnable() {
22980            @Override
22981            public void run() {
22982                unloadPrivatePackagesInner(vol);
22983            }
22984        });
22985    }
22986
22987    private void unloadPrivatePackagesInner(VolumeInfo vol) {
22988        final String volumeUuid = vol.fsUuid;
22989        if (TextUtils.isEmpty(volumeUuid)) {
22990            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
22991            return;
22992        }
22993
22994        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
22995        synchronized (mInstallLock) {
22996        synchronized (mPackages) {
22997            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
22998            for (PackageSetting ps : packages) {
22999                if (ps.pkg == null) continue;
23000
23001                final ApplicationInfo info = ps.pkg.applicationInfo;
23002                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
23003                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
23004
23005                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
23006                        "unloadPrivatePackagesInner")) {
23007                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
23008                            false, null)) {
23009                        unloaded.add(info);
23010                    } else {
23011                        Slog.w(TAG, "Failed to unload " + ps.codePath);
23012                    }
23013                }
23014
23015                // Try very hard to release any references to this package
23016                // so we don't risk the system server being killed due to
23017                // open FDs
23018                AttributeCache.instance().removePackage(ps.name);
23019            }
23020
23021            mSettings.writeLPr();
23022        }
23023        }
23024
23025        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
23026        sendResourcesChangedBroadcast(false, false, unloaded, null);
23027
23028        // Try very hard to release any references to this path so we don't risk
23029        // the system server being killed due to open FDs
23030        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
23031
23032        for (int i = 0; i < 3; i++) {
23033            System.gc();
23034            System.runFinalization();
23035        }
23036    }
23037
23038    private void assertPackageKnown(String volumeUuid, String packageName)
23039            throws PackageManagerException {
23040        synchronized (mPackages) {
23041            // Normalize package name to handle renamed packages
23042            packageName = normalizePackageNameLPr(packageName);
23043
23044            final PackageSetting ps = mSettings.mPackages.get(packageName);
23045            if (ps == null) {
23046                throw new PackageManagerException("Package " + packageName + " is unknown");
23047            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23048                throw new PackageManagerException(
23049                        "Package " + packageName + " found on unknown volume " + volumeUuid
23050                                + "; expected volume " + ps.volumeUuid);
23051            }
23052        }
23053    }
23054
23055    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
23056            throws PackageManagerException {
23057        synchronized (mPackages) {
23058            // Normalize package name to handle renamed packages
23059            packageName = normalizePackageNameLPr(packageName);
23060
23061            final PackageSetting ps = mSettings.mPackages.get(packageName);
23062            if (ps == null) {
23063                throw new PackageManagerException("Package " + packageName + " is unknown");
23064            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23065                throw new PackageManagerException(
23066                        "Package " + packageName + " found on unknown volume " + volumeUuid
23067                                + "; expected volume " + ps.volumeUuid);
23068            } else if (!ps.getInstalled(userId)) {
23069                throw new PackageManagerException(
23070                        "Package " + packageName + " not installed for user " + userId);
23071            }
23072        }
23073    }
23074
23075    private List<String> collectAbsoluteCodePaths() {
23076        synchronized (mPackages) {
23077            List<String> codePaths = new ArrayList<>();
23078            final int packageCount = mSettings.mPackages.size();
23079            for (int i = 0; i < packageCount; i++) {
23080                final PackageSetting ps = mSettings.mPackages.valueAt(i);
23081                codePaths.add(ps.codePath.getAbsolutePath());
23082            }
23083            return codePaths;
23084        }
23085    }
23086
23087    /**
23088     * Examine all apps present on given mounted volume, and destroy apps that
23089     * aren't expected, either due to uninstallation or reinstallation on
23090     * another volume.
23091     */
23092    private void reconcileApps(String volumeUuid) {
23093        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
23094        List<File> filesToDelete = null;
23095
23096        final File[] files = FileUtils.listFilesOrEmpty(
23097                Environment.getDataAppDirectory(volumeUuid));
23098        for (File file : files) {
23099            final boolean isPackage = (isApkFile(file) || file.isDirectory())
23100                    && !PackageInstallerService.isStageName(file.getName());
23101            if (!isPackage) {
23102                // Ignore entries which are not packages
23103                continue;
23104            }
23105
23106            String absolutePath = file.getAbsolutePath();
23107
23108            boolean pathValid = false;
23109            final int absoluteCodePathCount = absoluteCodePaths.size();
23110            for (int i = 0; i < absoluteCodePathCount; i++) {
23111                String absoluteCodePath = absoluteCodePaths.get(i);
23112                if (absolutePath.startsWith(absoluteCodePath)) {
23113                    pathValid = true;
23114                    break;
23115                }
23116            }
23117
23118            if (!pathValid) {
23119                if (filesToDelete == null) {
23120                    filesToDelete = new ArrayList<>();
23121                }
23122                filesToDelete.add(file);
23123            }
23124        }
23125
23126        if (filesToDelete != null) {
23127            final int fileToDeleteCount = filesToDelete.size();
23128            for (int i = 0; i < fileToDeleteCount; i++) {
23129                File fileToDelete = filesToDelete.get(i);
23130                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
23131                synchronized (mInstallLock) {
23132                    removeCodePathLI(fileToDelete);
23133                }
23134            }
23135        }
23136    }
23137
23138    /**
23139     * Reconcile all app data for the given user.
23140     * <p>
23141     * Verifies that directories exist and that ownership and labeling is
23142     * correct for all installed apps on all mounted volumes.
23143     */
23144    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
23145        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23146        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
23147            final String volumeUuid = vol.getFsUuid();
23148            synchronized (mInstallLock) {
23149                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
23150            }
23151        }
23152    }
23153
23154    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23155            boolean migrateAppData) {
23156        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
23157    }
23158
23159    /**
23160     * Reconcile all app data on given mounted volume.
23161     * <p>
23162     * Destroys app data that isn't expected, either due to uninstallation or
23163     * reinstallation on another volume.
23164     * <p>
23165     * Verifies that directories exist and that ownership and labeling is
23166     * correct for all installed apps.
23167     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
23168     */
23169    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23170            boolean migrateAppData, boolean onlyCoreApps) {
23171        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
23172                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
23173        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
23174
23175        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
23176        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
23177
23178        // First look for stale data that doesn't belong, and check if things
23179        // have changed since we did our last restorecon
23180        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
23181            if (StorageManager.isFileEncryptedNativeOrEmulated()
23182                    && !StorageManager.isUserKeyUnlocked(userId)) {
23183                throw new RuntimeException(
23184                        "Yikes, someone asked us to reconcile CE storage while " + userId
23185                                + " was still locked; this would have caused massive data loss!");
23186            }
23187
23188            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
23189            for (File file : files) {
23190                final String packageName = file.getName();
23191                try {
23192                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
23193                } catch (PackageManagerException e) {
23194                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
23195                    try {
23196                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
23197                                StorageManager.FLAG_STORAGE_CE, 0);
23198                    } catch (InstallerException e2) {
23199                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
23200                    }
23201                }
23202            }
23203        }
23204        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
23205            final File[] files = FileUtils.listFilesOrEmpty(deDir);
23206            for (File file : files) {
23207                final String packageName = file.getName();
23208                try {
23209                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
23210                } catch (PackageManagerException e) {
23211                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
23212                    try {
23213                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
23214                                StorageManager.FLAG_STORAGE_DE, 0);
23215                    } catch (InstallerException e2) {
23216                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
23217                    }
23218                }
23219            }
23220        }
23221
23222        // Ensure that data directories are ready to roll for all packages
23223        // installed for this volume and user
23224        final List<PackageSetting> packages;
23225        synchronized (mPackages) {
23226            packages = mSettings.getVolumePackagesLPr(volumeUuid);
23227        }
23228        int preparedCount = 0;
23229        for (PackageSetting ps : packages) {
23230            final String packageName = ps.name;
23231            if (ps.pkg == null) {
23232                Slog.w(TAG, "Odd, missing scanned package " + packageName);
23233                // TODO: might be due to legacy ASEC apps; we should circle back
23234                // and reconcile again once they're scanned
23235                continue;
23236            }
23237            // Skip non-core apps if requested
23238            if (onlyCoreApps && !ps.pkg.coreApp) {
23239                result.add(packageName);
23240                continue;
23241            }
23242
23243            if (ps.getInstalled(userId)) {
23244                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
23245                preparedCount++;
23246            }
23247        }
23248
23249        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
23250        return result;
23251    }
23252
23253    /**
23254     * Prepare app data for the given app just after it was installed or
23255     * upgraded. This method carefully only touches users that it's installed
23256     * for, and it forces a restorecon to handle any seinfo changes.
23257     * <p>
23258     * Verifies that directories exist and that ownership and labeling is
23259     * correct for all installed apps. If there is an ownership mismatch, it
23260     * will try recovering system apps by wiping data; third-party app data is
23261     * left intact.
23262     * <p>
23263     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
23264     */
23265    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
23266        final PackageSetting ps;
23267        synchronized (mPackages) {
23268            ps = mSettings.mPackages.get(pkg.packageName);
23269            mSettings.writeKernelMappingLPr(ps);
23270        }
23271
23272        final UserManager um = mContext.getSystemService(UserManager.class);
23273        UserManagerInternal umInternal = getUserManagerInternal();
23274        for (UserInfo user : um.getUsers()) {
23275            final int flags;
23276            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
23277                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
23278            } else if (umInternal.isUserRunning(user.id)) {
23279                flags = StorageManager.FLAG_STORAGE_DE;
23280            } else {
23281                continue;
23282            }
23283
23284            if (ps.getInstalled(user.id)) {
23285                // TODO: when user data is locked, mark that we're still dirty
23286                prepareAppDataLIF(pkg, user.id, flags);
23287            }
23288        }
23289    }
23290
23291    /**
23292     * Prepare app data for the given app.
23293     * <p>
23294     * Verifies that directories exist and that ownership and labeling is
23295     * correct for all installed apps. If there is an ownership mismatch, this
23296     * will try recovering system apps by wiping data; third-party app data is
23297     * left intact.
23298     */
23299    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
23300        if (pkg == null) {
23301            Slog.wtf(TAG, "Package was null!", new Throwable());
23302            return;
23303        }
23304        prepareAppDataLeafLIF(pkg, userId, flags);
23305        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
23306        for (int i = 0; i < childCount; i++) {
23307            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
23308        }
23309    }
23310
23311    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
23312            boolean maybeMigrateAppData) {
23313        prepareAppDataLIF(pkg, userId, flags);
23314
23315        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
23316            // We may have just shuffled around app data directories, so
23317            // prepare them one more time
23318            prepareAppDataLIF(pkg, userId, flags);
23319        }
23320    }
23321
23322    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
23323        if (DEBUG_APP_DATA) {
23324            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
23325                    + Integer.toHexString(flags));
23326        }
23327
23328        final String volumeUuid = pkg.volumeUuid;
23329        final String packageName = pkg.packageName;
23330        final ApplicationInfo app = pkg.applicationInfo;
23331        final int appId = UserHandle.getAppId(app.uid);
23332
23333        Preconditions.checkNotNull(app.seInfo);
23334
23335        long ceDataInode = -1;
23336        try {
23337            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
23338                    appId, app.seInfo, app.targetSdkVersion);
23339        } catch (InstallerException e) {
23340            if (app.isSystemApp()) {
23341                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
23342                        + ", but trying to recover: " + e);
23343                destroyAppDataLeafLIF(pkg, userId, flags);
23344                try {
23345                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
23346                            appId, app.seInfo, app.targetSdkVersion);
23347                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
23348                } catch (InstallerException e2) {
23349                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
23350                }
23351            } else {
23352                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
23353            }
23354        }
23355
23356        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
23357            // TODO: mark this structure as dirty so we persist it!
23358            synchronized (mPackages) {
23359                final PackageSetting ps = mSettings.mPackages.get(packageName);
23360                if (ps != null) {
23361                    ps.setCeDataInode(ceDataInode, userId);
23362                }
23363            }
23364        }
23365
23366        prepareAppDataContentsLeafLIF(pkg, userId, flags);
23367    }
23368
23369    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
23370        if (pkg == null) {
23371            Slog.wtf(TAG, "Package was null!", new Throwable());
23372            return;
23373        }
23374        prepareAppDataContentsLeafLIF(pkg, userId, flags);
23375        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
23376        for (int i = 0; i < childCount; i++) {
23377            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
23378        }
23379    }
23380
23381    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
23382        final String volumeUuid = pkg.volumeUuid;
23383        final String packageName = pkg.packageName;
23384        final ApplicationInfo app = pkg.applicationInfo;
23385
23386        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
23387            // Create a native library symlink only if we have native libraries
23388            // and if the native libraries are 32 bit libraries. We do not provide
23389            // this symlink for 64 bit libraries.
23390            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
23391                final String nativeLibPath = app.nativeLibraryDir;
23392                try {
23393                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
23394                            nativeLibPath, userId);
23395                } catch (InstallerException e) {
23396                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
23397                }
23398            }
23399        }
23400    }
23401
23402    /**
23403     * For system apps on non-FBE devices, this method migrates any existing
23404     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
23405     * requested by the app.
23406     */
23407    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
23408        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
23409                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
23410            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
23411                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
23412            try {
23413                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
23414                        storageTarget);
23415            } catch (InstallerException e) {
23416                logCriticalInfo(Log.WARN,
23417                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
23418            }
23419            return true;
23420        } else {
23421            return false;
23422        }
23423    }
23424
23425    public PackageFreezer freezePackage(String packageName, String killReason) {
23426        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
23427    }
23428
23429    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
23430        return new PackageFreezer(packageName, userId, killReason);
23431    }
23432
23433    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
23434            String killReason) {
23435        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
23436    }
23437
23438    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
23439            String killReason) {
23440        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
23441            return new PackageFreezer();
23442        } else {
23443            return freezePackage(packageName, userId, killReason);
23444        }
23445    }
23446
23447    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
23448            String killReason) {
23449        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
23450    }
23451
23452    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
23453            String killReason) {
23454        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
23455            return new PackageFreezer();
23456        } else {
23457            return freezePackage(packageName, userId, killReason);
23458        }
23459    }
23460
23461    /**
23462     * Class that freezes and kills the given package upon creation, and
23463     * unfreezes it upon closing. This is typically used when doing surgery on
23464     * app code/data to prevent the app from running while you're working.
23465     */
23466    private class PackageFreezer implements AutoCloseable {
23467        private final String mPackageName;
23468        private final PackageFreezer[] mChildren;
23469
23470        private final boolean mWeFroze;
23471
23472        private final AtomicBoolean mClosed = new AtomicBoolean();
23473        private final CloseGuard mCloseGuard = CloseGuard.get();
23474
23475        /**
23476         * Create and return a stub freezer that doesn't actually do anything,
23477         * typically used when someone requested
23478         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
23479         * {@link PackageManager#DELETE_DONT_KILL_APP}.
23480         */
23481        public PackageFreezer() {
23482            mPackageName = null;
23483            mChildren = null;
23484            mWeFroze = false;
23485            mCloseGuard.open("close");
23486        }
23487
23488        public PackageFreezer(String packageName, int userId, String killReason) {
23489            synchronized (mPackages) {
23490                mPackageName = packageName;
23491                mWeFroze = mFrozenPackages.add(mPackageName);
23492
23493                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
23494                if (ps != null) {
23495                    killApplication(ps.name, ps.appId, userId, killReason);
23496                }
23497
23498                final PackageParser.Package p = mPackages.get(packageName);
23499                if (p != null && p.childPackages != null) {
23500                    final int N = p.childPackages.size();
23501                    mChildren = new PackageFreezer[N];
23502                    for (int i = 0; i < N; i++) {
23503                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
23504                                userId, killReason);
23505                    }
23506                } else {
23507                    mChildren = null;
23508                }
23509            }
23510            mCloseGuard.open("close");
23511        }
23512
23513        @Override
23514        protected void finalize() throws Throwable {
23515            try {
23516                mCloseGuard.warnIfOpen();
23517                close();
23518            } finally {
23519                super.finalize();
23520            }
23521        }
23522
23523        @Override
23524        public void close() {
23525            mCloseGuard.close();
23526            if (mClosed.compareAndSet(false, true)) {
23527                synchronized (mPackages) {
23528                    if (mWeFroze) {
23529                        mFrozenPackages.remove(mPackageName);
23530                    }
23531
23532                    if (mChildren != null) {
23533                        for (PackageFreezer freezer : mChildren) {
23534                            freezer.close();
23535                        }
23536                    }
23537                }
23538            }
23539        }
23540    }
23541
23542    /**
23543     * Verify that given package is currently frozen.
23544     */
23545    private void checkPackageFrozen(String packageName) {
23546        synchronized (mPackages) {
23547            if (!mFrozenPackages.contains(packageName)) {
23548                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
23549            }
23550        }
23551    }
23552
23553    @Override
23554    public int movePackage(final String packageName, final String volumeUuid) {
23555        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
23556
23557        final int callingUid = Binder.getCallingUid();
23558        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
23559        final int moveId = mNextMoveId.getAndIncrement();
23560        mHandler.post(new Runnable() {
23561            @Override
23562            public void run() {
23563                try {
23564                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
23565                } catch (PackageManagerException e) {
23566                    Slog.w(TAG, "Failed to move " + packageName, e);
23567                    mMoveCallbacks.notifyStatusChanged(moveId,
23568                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
23569                }
23570            }
23571        });
23572        return moveId;
23573    }
23574
23575    private void movePackageInternal(final String packageName, final String volumeUuid,
23576            final int moveId, final int callingUid, UserHandle user)
23577                    throws PackageManagerException {
23578        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23579        final PackageManager pm = mContext.getPackageManager();
23580
23581        final boolean currentAsec;
23582        final String currentVolumeUuid;
23583        final File codeFile;
23584        final String installerPackageName;
23585        final String packageAbiOverride;
23586        final int appId;
23587        final String seinfo;
23588        final String label;
23589        final int targetSdkVersion;
23590        final PackageFreezer freezer;
23591        final int[] installedUserIds;
23592
23593        // reader
23594        synchronized (mPackages) {
23595            final PackageParser.Package pkg = mPackages.get(packageName);
23596            final PackageSetting ps = mSettings.mPackages.get(packageName);
23597            if (pkg == null
23598                    || ps == null
23599                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
23600                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
23601            }
23602            if (pkg.applicationInfo.isSystemApp()) {
23603                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
23604                        "Cannot move system application");
23605            }
23606
23607            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
23608            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
23609                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
23610            if (isInternalStorage && !allow3rdPartyOnInternal) {
23611                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
23612                        "3rd party apps are not allowed on internal storage");
23613            }
23614
23615            if (pkg.applicationInfo.isExternalAsec()) {
23616                currentAsec = true;
23617                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
23618            } else if (pkg.applicationInfo.isForwardLocked()) {
23619                currentAsec = true;
23620                currentVolumeUuid = "forward_locked";
23621            } else {
23622                currentAsec = false;
23623                currentVolumeUuid = ps.volumeUuid;
23624
23625                final File probe = new File(pkg.codePath);
23626                final File probeOat = new File(probe, "oat");
23627                if (!probe.isDirectory() || !probeOat.isDirectory()) {
23628                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23629                            "Move only supported for modern cluster style installs");
23630                }
23631            }
23632
23633            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
23634                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23635                        "Package already moved to " + volumeUuid);
23636            }
23637            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
23638                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
23639                        "Device admin cannot be moved");
23640            }
23641
23642            if (mFrozenPackages.contains(packageName)) {
23643                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
23644                        "Failed to move already frozen package");
23645            }
23646
23647            codeFile = new File(pkg.codePath);
23648            installerPackageName = ps.installerPackageName;
23649            packageAbiOverride = ps.cpuAbiOverrideString;
23650            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
23651            seinfo = pkg.applicationInfo.seInfo;
23652            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
23653            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
23654            freezer = freezePackage(packageName, "movePackageInternal");
23655            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
23656        }
23657
23658        final Bundle extras = new Bundle();
23659        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
23660        extras.putString(Intent.EXTRA_TITLE, label);
23661        mMoveCallbacks.notifyCreated(moveId, extras);
23662
23663        int installFlags;
23664        final boolean moveCompleteApp;
23665        final File measurePath;
23666
23667        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
23668            installFlags = INSTALL_INTERNAL;
23669            moveCompleteApp = !currentAsec;
23670            measurePath = Environment.getDataAppDirectory(volumeUuid);
23671        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
23672            installFlags = INSTALL_EXTERNAL;
23673            moveCompleteApp = false;
23674            measurePath = storage.getPrimaryPhysicalVolume().getPath();
23675        } else {
23676            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
23677            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
23678                    || !volume.isMountedWritable()) {
23679                freezer.close();
23680                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23681                        "Move location not mounted private volume");
23682            }
23683
23684            Preconditions.checkState(!currentAsec);
23685
23686            installFlags = INSTALL_INTERNAL;
23687            moveCompleteApp = true;
23688            measurePath = Environment.getDataAppDirectory(volumeUuid);
23689        }
23690
23691        final PackageStats stats = new PackageStats(null, -1);
23692        synchronized (mInstaller) {
23693            for (int userId : installedUserIds) {
23694                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
23695                    freezer.close();
23696                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23697                            "Failed to measure package size");
23698                }
23699            }
23700        }
23701
23702        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
23703                + stats.dataSize);
23704
23705        final long startFreeBytes = measurePath.getUsableSpace();
23706        final long sizeBytes;
23707        if (moveCompleteApp) {
23708            sizeBytes = stats.codeSize + stats.dataSize;
23709        } else {
23710            sizeBytes = stats.codeSize;
23711        }
23712
23713        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
23714            freezer.close();
23715            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23716                    "Not enough free space to move");
23717        }
23718
23719        mMoveCallbacks.notifyStatusChanged(moveId, 10);
23720
23721        final CountDownLatch installedLatch = new CountDownLatch(1);
23722        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
23723            @Override
23724            public void onUserActionRequired(Intent intent) throws RemoteException {
23725                throw new IllegalStateException();
23726            }
23727
23728            @Override
23729            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
23730                    Bundle extras) throws RemoteException {
23731                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
23732                        + PackageManager.installStatusToString(returnCode, msg));
23733
23734                installedLatch.countDown();
23735                freezer.close();
23736
23737                final int status = PackageManager.installStatusToPublicStatus(returnCode);
23738                switch (status) {
23739                    case PackageInstaller.STATUS_SUCCESS:
23740                        mMoveCallbacks.notifyStatusChanged(moveId,
23741                                PackageManager.MOVE_SUCCEEDED);
23742                        break;
23743                    case PackageInstaller.STATUS_FAILURE_STORAGE:
23744                        mMoveCallbacks.notifyStatusChanged(moveId,
23745                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
23746                        break;
23747                    default:
23748                        mMoveCallbacks.notifyStatusChanged(moveId,
23749                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
23750                        break;
23751                }
23752            }
23753        };
23754
23755        final MoveInfo move;
23756        if (moveCompleteApp) {
23757            // Kick off a thread to report progress estimates
23758            new Thread() {
23759                @Override
23760                public void run() {
23761                    while (true) {
23762                        try {
23763                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
23764                                break;
23765                            }
23766                        } catch (InterruptedException ignored) {
23767                        }
23768
23769                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
23770                        final int progress = 10 + (int) MathUtils.constrain(
23771                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
23772                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
23773                    }
23774                }
23775            }.start();
23776
23777            final String dataAppName = codeFile.getName();
23778            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
23779                    dataAppName, appId, seinfo, targetSdkVersion);
23780        } else {
23781            move = null;
23782        }
23783
23784        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
23785
23786        final Message msg = mHandler.obtainMessage(INIT_COPY);
23787        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
23788        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
23789                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
23790                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
23791                PackageManager.INSTALL_REASON_UNKNOWN);
23792        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
23793        msg.obj = params;
23794
23795        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
23796                System.identityHashCode(msg.obj));
23797        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
23798                System.identityHashCode(msg.obj));
23799
23800        mHandler.sendMessage(msg);
23801    }
23802
23803    @Override
23804    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
23805        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
23806
23807        final int realMoveId = mNextMoveId.getAndIncrement();
23808        final Bundle extras = new Bundle();
23809        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
23810        mMoveCallbacks.notifyCreated(realMoveId, extras);
23811
23812        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
23813            @Override
23814            public void onCreated(int moveId, Bundle extras) {
23815                // Ignored
23816            }
23817
23818            @Override
23819            public void onStatusChanged(int moveId, int status, long estMillis) {
23820                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
23821            }
23822        };
23823
23824        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23825        storage.setPrimaryStorageUuid(volumeUuid, callback);
23826        return realMoveId;
23827    }
23828
23829    @Override
23830    public int getMoveStatus(int moveId) {
23831        mContext.enforceCallingOrSelfPermission(
23832                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23833        return mMoveCallbacks.mLastStatus.get(moveId);
23834    }
23835
23836    @Override
23837    public void registerMoveCallback(IPackageMoveObserver callback) {
23838        mContext.enforceCallingOrSelfPermission(
23839                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23840        mMoveCallbacks.register(callback);
23841    }
23842
23843    @Override
23844    public void unregisterMoveCallback(IPackageMoveObserver callback) {
23845        mContext.enforceCallingOrSelfPermission(
23846                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23847        mMoveCallbacks.unregister(callback);
23848    }
23849
23850    @Override
23851    public boolean setInstallLocation(int loc) {
23852        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
23853                null);
23854        if (getInstallLocation() == loc) {
23855            return true;
23856        }
23857        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
23858                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
23859            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
23860                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
23861            return true;
23862        }
23863        return false;
23864   }
23865
23866    @Override
23867    public int getInstallLocation() {
23868        // allow instant app access
23869        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
23870                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
23871                PackageHelper.APP_INSTALL_AUTO);
23872    }
23873
23874    /** Called by UserManagerService */
23875    void cleanUpUser(UserManagerService userManager, int userHandle) {
23876        synchronized (mPackages) {
23877            mDirtyUsers.remove(userHandle);
23878            mUserNeedsBadging.delete(userHandle);
23879            mSettings.removeUserLPw(userHandle);
23880            mPendingBroadcasts.remove(userHandle);
23881            mInstantAppRegistry.onUserRemovedLPw(userHandle);
23882            removeUnusedPackagesLPw(userManager, userHandle);
23883        }
23884    }
23885
23886    /**
23887     * We're removing userHandle and would like to remove any downloaded packages
23888     * that are no longer in use by any other user.
23889     * @param userHandle the user being removed
23890     */
23891    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
23892        final boolean DEBUG_CLEAN_APKS = false;
23893        int [] users = userManager.getUserIds();
23894        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
23895        while (psit.hasNext()) {
23896            PackageSetting ps = psit.next();
23897            if (ps.pkg == null) {
23898                continue;
23899            }
23900            final String packageName = ps.pkg.packageName;
23901            // Skip over if system app
23902            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
23903                continue;
23904            }
23905            if (DEBUG_CLEAN_APKS) {
23906                Slog.i(TAG, "Checking package " + packageName);
23907            }
23908            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
23909            if (keep) {
23910                if (DEBUG_CLEAN_APKS) {
23911                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
23912                }
23913            } else {
23914                for (int i = 0; i < users.length; i++) {
23915                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
23916                        keep = true;
23917                        if (DEBUG_CLEAN_APKS) {
23918                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
23919                                    + users[i]);
23920                        }
23921                        break;
23922                    }
23923                }
23924            }
23925            if (!keep) {
23926                if (DEBUG_CLEAN_APKS) {
23927                    Slog.i(TAG, "  Removing package " + packageName);
23928                }
23929                mHandler.post(new Runnable() {
23930                    public void run() {
23931                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
23932                                userHandle, 0);
23933                    } //end run
23934                });
23935            }
23936        }
23937    }
23938
23939    /** Called by UserManagerService */
23940    void createNewUser(int userId, String[] disallowedPackages) {
23941        synchronized (mInstallLock) {
23942            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
23943        }
23944        synchronized (mPackages) {
23945            scheduleWritePackageRestrictionsLocked(userId);
23946            scheduleWritePackageListLocked(userId);
23947            applyFactoryDefaultBrowserLPw(userId);
23948            primeDomainVerificationsLPw(userId);
23949        }
23950    }
23951
23952    void onNewUserCreated(final int userId) {
23953        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
23954        // If permission review for legacy apps is required, we represent
23955        // dagerous permissions for such apps as always granted runtime
23956        // permissions to keep per user flag state whether review is needed.
23957        // Hence, if a new user is added we have to propagate dangerous
23958        // permission grants for these legacy apps.
23959        if (mPermissionReviewRequired) {
23960            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
23961                    | UPDATE_PERMISSIONS_REPLACE_ALL);
23962        }
23963    }
23964
23965    @Override
23966    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
23967        mContext.enforceCallingOrSelfPermission(
23968                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
23969                "Only package verification agents can read the verifier device identity");
23970
23971        synchronized (mPackages) {
23972            return mSettings.getVerifierDeviceIdentityLPw();
23973        }
23974    }
23975
23976    @Override
23977    public void setPermissionEnforced(String permission, boolean enforced) {
23978        // TODO: Now that we no longer change GID for storage, this should to away.
23979        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
23980                "setPermissionEnforced");
23981        if (READ_EXTERNAL_STORAGE.equals(permission)) {
23982            synchronized (mPackages) {
23983                if (mSettings.mReadExternalStorageEnforced == null
23984                        || mSettings.mReadExternalStorageEnforced != enforced) {
23985                    mSettings.mReadExternalStorageEnforced = enforced;
23986                    mSettings.writeLPr();
23987                }
23988            }
23989            // kill any non-foreground processes so we restart them and
23990            // grant/revoke the GID.
23991            final IActivityManager am = ActivityManager.getService();
23992            if (am != null) {
23993                final long token = Binder.clearCallingIdentity();
23994                try {
23995                    am.killProcessesBelowForeground("setPermissionEnforcement");
23996                } catch (RemoteException e) {
23997                } finally {
23998                    Binder.restoreCallingIdentity(token);
23999                }
24000            }
24001        } else {
24002            throw new IllegalArgumentException("No selective enforcement for " + permission);
24003        }
24004    }
24005
24006    @Override
24007    @Deprecated
24008    public boolean isPermissionEnforced(String permission) {
24009        // allow instant applications
24010        return true;
24011    }
24012
24013    @Override
24014    public boolean isStorageLow() {
24015        // allow instant applications
24016        final long token = Binder.clearCallingIdentity();
24017        try {
24018            final DeviceStorageMonitorInternal
24019                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
24020            if (dsm != null) {
24021                return dsm.isMemoryLow();
24022            } else {
24023                return false;
24024            }
24025        } finally {
24026            Binder.restoreCallingIdentity(token);
24027        }
24028    }
24029
24030    @Override
24031    public IPackageInstaller getPackageInstaller() {
24032        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24033            return null;
24034        }
24035        return mInstallerService;
24036    }
24037
24038    private boolean userNeedsBadging(int userId) {
24039        int index = mUserNeedsBadging.indexOfKey(userId);
24040        if (index < 0) {
24041            final UserInfo userInfo;
24042            final long token = Binder.clearCallingIdentity();
24043            try {
24044                userInfo = sUserManager.getUserInfo(userId);
24045            } finally {
24046                Binder.restoreCallingIdentity(token);
24047            }
24048            final boolean b;
24049            if (userInfo != null && userInfo.isManagedProfile()) {
24050                b = true;
24051            } else {
24052                b = false;
24053            }
24054            mUserNeedsBadging.put(userId, b);
24055            return b;
24056        }
24057        return mUserNeedsBadging.valueAt(index);
24058    }
24059
24060    @Override
24061    public KeySet getKeySetByAlias(String packageName, String alias) {
24062        if (packageName == null || alias == null) {
24063            return null;
24064        }
24065        synchronized(mPackages) {
24066            final PackageParser.Package pkg = mPackages.get(packageName);
24067            if (pkg == null) {
24068                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24069                throw new IllegalArgumentException("Unknown package: " + packageName);
24070            }
24071            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24072            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
24073                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
24074                throw new IllegalArgumentException("Unknown package: " + packageName);
24075            }
24076            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24077            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
24078        }
24079    }
24080
24081    @Override
24082    public KeySet getSigningKeySet(String packageName) {
24083        if (packageName == null) {
24084            return null;
24085        }
24086        synchronized(mPackages) {
24087            final int callingUid = Binder.getCallingUid();
24088            final int callingUserId = UserHandle.getUserId(callingUid);
24089            final PackageParser.Package pkg = mPackages.get(packageName);
24090            if (pkg == null) {
24091                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24092                throw new IllegalArgumentException("Unknown package: " + packageName);
24093            }
24094            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24095            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
24096                // filter and pretend the package doesn't exist
24097                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
24098                        + ", uid:" + callingUid);
24099                throw new IllegalArgumentException("Unknown package: " + packageName);
24100            }
24101            if (pkg.applicationInfo.uid != callingUid
24102                    && Process.SYSTEM_UID != callingUid) {
24103                throw new SecurityException("May not access signing KeySet of other apps.");
24104            }
24105            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24106            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
24107        }
24108    }
24109
24110    @Override
24111    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
24112        final int callingUid = Binder.getCallingUid();
24113        if (getInstantAppPackageName(callingUid) != null) {
24114            return false;
24115        }
24116        if (packageName == null || ks == null) {
24117            return false;
24118        }
24119        synchronized(mPackages) {
24120            final PackageParser.Package pkg = mPackages.get(packageName);
24121            if (pkg == null
24122                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24123                            UserHandle.getUserId(callingUid))) {
24124                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24125                throw new IllegalArgumentException("Unknown package: " + packageName);
24126            }
24127            IBinder ksh = ks.getToken();
24128            if (ksh instanceof KeySetHandle) {
24129                KeySetManagerService ksms = mSettings.mKeySetManagerService;
24130                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
24131            }
24132            return false;
24133        }
24134    }
24135
24136    @Override
24137    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
24138        final int callingUid = Binder.getCallingUid();
24139        if (getInstantAppPackageName(callingUid) != null) {
24140            return false;
24141        }
24142        if (packageName == null || ks == null) {
24143            return false;
24144        }
24145        synchronized(mPackages) {
24146            final PackageParser.Package pkg = mPackages.get(packageName);
24147            if (pkg == null
24148                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24149                            UserHandle.getUserId(callingUid))) {
24150                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24151                throw new IllegalArgumentException("Unknown package: " + packageName);
24152            }
24153            IBinder ksh = ks.getToken();
24154            if (ksh instanceof KeySetHandle) {
24155                KeySetManagerService ksms = mSettings.mKeySetManagerService;
24156                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
24157            }
24158            return false;
24159        }
24160    }
24161
24162    private void deletePackageIfUnusedLPr(final String packageName) {
24163        PackageSetting ps = mSettings.mPackages.get(packageName);
24164        if (ps == null) {
24165            return;
24166        }
24167        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
24168            // TODO Implement atomic delete if package is unused
24169            // It is currently possible that the package will be deleted even if it is installed
24170            // after this method returns.
24171            mHandler.post(new Runnable() {
24172                public void run() {
24173                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
24174                            0, PackageManager.DELETE_ALL_USERS);
24175                }
24176            });
24177        }
24178    }
24179
24180    /**
24181     * Check and throw if the given before/after packages would be considered a
24182     * downgrade.
24183     */
24184    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
24185            throws PackageManagerException {
24186        if (after.versionCode < before.mVersionCode) {
24187            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24188                    "Update version code " + after.versionCode + " is older than current "
24189                    + before.mVersionCode);
24190        } else if (after.versionCode == before.mVersionCode) {
24191            if (after.baseRevisionCode < before.baseRevisionCode) {
24192                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24193                        "Update base revision code " + after.baseRevisionCode
24194                        + " is older than current " + before.baseRevisionCode);
24195            }
24196
24197            if (!ArrayUtils.isEmpty(after.splitNames)) {
24198                for (int i = 0; i < after.splitNames.length; i++) {
24199                    final String splitName = after.splitNames[i];
24200                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
24201                    if (j != -1) {
24202                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
24203                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24204                                    "Update split " + splitName + " revision code "
24205                                    + after.splitRevisionCodes[i] + " is older than current "
24206                                    + before.splitRevisionCodes[j]);
24207                        }
24208                    }
24209                }
24210            }
24211        }
24212    }
24213
24214    private static class MoveCallbacks extends Handler {
24215        private static final int MSG_CREATED = 1;
24216        private static final int MSG_STATUS_CHANGED = 2;
24217
24218        private final RemoteCallbackList<IPackageMoveObserver>
24219                mCallbacks = new RemoteCallbackList<>();
24220
24221        private final SparseIntArray mLastStatus = new SparseIntArray();
24222
24223        public MoveCallbacks(Looper looper) {
24224            super(looper);
24225        }
24226
24227        public void register(IPackageMoveObserver callback) {
24228            mCallbacks.register(callback);
24229        }
24230
24231        public void unregister(IPackageMoveObserver callback) {
24232            mCallbacks.unregister(callback);
24233        }
24234
24235        @Override
24236        public void handleMessage(Message msg) {
24237            final SomeArgs args = (SomeArgs) msg.obj;
24238            final int n = mCallbacks.beginBroadcast();
24239            for (int i = 0; i < n; i++) {
24240                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
24241                try {
24242                    invokeCallback(callback, msg.what, args);
24243                } catch (RemoteException ignored) {
24244                }
24245            }
24246            mCallbacks.finishBroadcast();
24247            args.recycle();
24248        }
24249
24250        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
24251                throws RemoteException {
24252            switch (what) {
24253                case MSG_CREATED: {
24254                    callback.onCreated(args.argi1, (Bundle) args.arg2);
24255                    break;
24256                }
24257                case MSG_STATUS_CHANGED: {
24258                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
24259                    break;
24260                }
24261            }
24262        }
24263
24264        private void notifyCreated(int moveId, Bundle extras) {
24265            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
24266
24267            final SomeArgs args = SomeArgs.obtain();
24268            args.argi1 = moveId;
24269            args.arg2 = extras;
24270            obtainMessage(MSG_CREATED, args).sendToTarget();
24271        }
24272
24273        private void notifyStatusChanged(int moveId, int status) {
24274            notifyStatusChanged(moveId, status, -1);
24275        }
24276
24277        private void notifyStatusChanged(int moveId, int status, long estMillis) {
24278            Slog.v(TAG, "Move " + moveId + " status " + status);
24279
24280            final SomeArgs args = SomeArgs.obtain();
24281            args.argi1 = moveId;
24282            args.argi2 = status;
24283            args.arg3 = estMillis;
24284            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
24285
24286            synchronized (mLastStatus) {
24287                mLastStatus.put(moveId, status);
24288            }
24289        }
24290    }
24291
24292    private final static class OnPermissionChangeListeners extends Handler {
24293        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
24294
24295        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
24296                new RemoteCallbackList<>();
24297
24298        public OnPermissionChangeListeners(Looper looper) {
24299            super(looper);
24300        }
24301
24302        @Override
24303        public void handleMessage(Message msg) {
24304            switch (msg.what) {
24305                case MSG_ON_PERMISSIONS_CHANGED: {
24306                    final int uid = msg.arg1;
24307                    handleOnPermissionsChanged(uid);
24308                } break;
24309            }
24310        }
24311
24312        public void addListenerLocked(IOnPermissionsChangeListener listener) {
24313            mPermissionListeners.register(listener);
24314
24315        }
24316
24317        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
24318            mPermissionListeners.unregister(listener);
24319        }
24320
24321        public void onPermissionsChanged(int uid) {
24322            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
24323                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
24324            }
24325        }
24326
24327        private void handleOnPermissionsChanged(int uid) {
24328            final int count = mPermissionListeners.beginBroadcast();
24329            try {
24330                for (int i = 0; i < count; i++) {
24331                    IOnPermissionsChangeListener callback = mPermissionListeners
24332                            .getBroadcastItem(i);
24333                    try {
24334                        callback.onPermissionsChanged(uid);
24335                    } catch (RemoteException e) {
24336                        Log.e(TAG, "Permission listener is dead", e);
24337                    }
24338                }
24339            } finally {
24340                mPermissionListeners.finishBroadcast();
24341            }
24342        }
24343    }
24344
24345    private class PackageManagerInternalImpl extends PackageManagerInternal {
24346        @Override
24347        public void setLocationPackagesProvider(PackagesProvider provider) {
24348            synchronized (mPackages) {
24349                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
24350            }
24351        }
24352
24353        @Override
24354        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
24355            synchronized (mPackages) {
24356                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
24357            }
24358        }
24359
24360        @Override
24361        public void setSmsAppPackagesProvider(PackagesProvider provider) {
24362            synchronized (mPackages) {
24363                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
24364            }
24365        }
24366
24367        @Override
24368        public void setDialerAppPackagesProvider(PackagesProvider provider) {
24369            synchronized (mPackages) {
24370                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
24371            }
24372        }
24373
24374        @Override
24375        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
24376            synchronized (mPackages) {
24377                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
24378            }
24379        }
24380
24381        @Override
24382        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
24383            synchronized (mPackages) {
24384                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
24385            }
24386        }
24387
24388        @Override
24389        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
24390            synchronized (mPackages) {
24391                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
24392                        packageName, userId);
24393            }
24394        }
24395
24396        @Override
24397        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
24398            synchronized (mPackages) {
24399                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
24400                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
24401                        packageName, userId);
24402            }
24403        }
24404
24405        @Override
24406        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
24407            synchronized (mPackages) {
24408                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
24409                        packageName, userId);
24410            }
24411        }
24412
24413        @Override
24414        public void setKeepUninstalledPackages(final List<String> packageList) {
24415            Preconditions.checkNotNull(packageList);
24416            List<String> removedFromList = null;
24417            synchronized (mPackages) {
24418                if (mKeepUninstalledPackages != null) {
24419                    final int packagesCount = mKeepUninstalledPackages.size();
24420                    for (int i = 0; i < packagesCount; i++) {
24421                        String oldPackage = mKeepUninstalledPackages.get(i);
24422                        if (packageList != null && packageList.contains(oldPackage)) {
24423                            continue;
24424                        }
24425                        if (removedFromList == null) {
24426                            removedFromList = new ArrayList<>();
24427                        }
24428                        removedFromList.add(oldPackage);
24429                    }
24430                }
24431                mKeepUninstalledPackages = new ArrayList<>(packageList);
24432                if (removedFromList != null) {
24433                    final int removedCount = removedFromList.size();
24434                    for (int i = 0; i < removedCount; i++) {
24435                        deletePackageIfUnusedLPr(removedFromList.get(i));
24436                    }
24437                }
24438            }
24439        }
24440
24441        @Override
24442        public boolean isPermissionsReviewRequired(String packageName, int userId) {
24443            synchronized (mPackages) {
24444                // If we do not support permission review, done.
24445                if (!mPermissionReviewRequired) {
24446                    return false;
24447                }
24448
24449                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
24450                if (packageSetting == null) {
24451                    return false;
24452                }
24453
24454                // Permission review applies only to apps not supporting the new permission model.
24455                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
24456                    return false;
24457                }
24458
24459                // Legacy apps have the permission and get user consent on launch.
24460                PermissionsState permissionsState = packageSetting.getPermissionsState();
24461                return permissionsState.isPermissionReviewRequired(userId);
24462            }
24463        }
24464
24465        @Override
24466        public PackageInfo getPackageInfo(
24467                String packageName, int flags, int filterCallingUid, int userId) {
24468            return PackageManagerService.this
24469                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
24470                            flags, filterCallingUid, userId);
24471        }
24472
24473        @Override
24474        public ApplicationInfo getApplicationInfo(
24475                String packageName, int flags, int filterCallingUid, int userId) {
24476            return PackageManagerService.this
24477                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
24478        }
24479
24480        @Override
24481        public ActivityInfo getActivityInfo(
24482                ComponentName component, int flags, int filterCallingUid, int userId) {
24483            return PackageManagerService.this
24484                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
24485        }
24486
24487        @Override
24488        public List<ResolveInfo> queryIntentActivities(
24489                Intent intent, int flags, int filterCallingUid, int userId) {
24490            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
24491            return PackageManagerService.this
24492                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
24493                            userId, false /*resolveForStart*/);
24494        }
24495
24496        @Override
24497        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
24498                int userId) {
24499            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
24500        }
24501
24502        @Override
24503        public void setDeviceAndProfileOwnerPackages(
24504                int deviceOwnerUserId, String deviceOwnerPackage,
24505                SparseArray<String> profileOwnerPackages) {
24506            mProtectedPackages.setDeviceAndProfileOwnerPackages(
24507                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
24508        }
24509
24510        @Override
24511        public boolean isPackageDataProtected(int userId, String packageName) {
24512            return mProtectedPackages.isPackageDataProtected(userId, packageName);
24513        }
24514
24515        @Override
24516        public boolean isPackageEphemeral(int userId, String packageName) {
24517            synchronized (mPackages) {
24518                final PackageSetting ps = mSettings.mPackages.get(packageName);
24519                return ps != null ? ps.getInstantApp(userId) : false;
24520            }
24521        }
24522
24523        @Override
24524        public boolean wasPackageEverLaunched(String packageName, int userId) {
24525            synchronized (mPackages) {
24526                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
24527            }
24528        }
24529
24530        @Override
24531        public void grantRuntimePermission(String packageName, String name, int userId,
24532                boolean overridePolicy) {
24533            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
24534                    overridePolicy);
24535        }
24536
24537        @Override
24538        public void revokeRuntimePermission(String packageName, String name, int userId,
24539                boolean overridePolicy) {
24540            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
24541                    overridePolicy);
24542        }
24543
24544        @Override
24545        public String getNameForUid(int uid) {
24546            return PackageManagerService.this.getNameForUid(uid);
24547        }
24548
24549        @Override
24550        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
24551                Intent origIntent, String resolvedType, String callingPackage,
24552                Bundle verificationBundle, int userId) {
24553            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
24554                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
24555                    userId);
24556        }
24557
24558        @Override
24559        public void grantEphemeralAccess(int userId, Intent intent,
24560                int targetAppId, int ephemeralAppId) {
24561            synchronized (mPackages) {
24562                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
24563                        targetAppId, ephemeralAppId);
24564            }
24565        }
24566
24567        @Override
24568        public boolean isInstantAppInstallerComponent(ComponentName component) {
24569            synchronized (mPackages) {
24570                return mInstantAppInstallerActivity != null
24571                        && mInstantAppInstallerActivity.getComponentName().equals(component);
24572            }
24573        }
24574
24575        @Override
24576        public void pruneInstantApps() {
24577            mInstantAppRegistry.pruneInstantApps();
24578        }
24579
24580        @Override
24581        public String getSetupWizardPackageName() {
24582            return mSetupWizardPackage;
24583        }
24584
24585        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
24586            if (policy != null) {
24587                mExternalSourcesPolicy = policy;
24588            }
24589        }
24590
24591        @Override
24592        public boolean isPackagePersistent(String packageName) {
24593            synchronized (mPackages) {
24594                PackageParser.Package pkg = mPackages.get(packageName);
24595                return pkg != null
24596                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
24597                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
24598                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
24599                        : false;
24600            }
24601        }
24602
24603        @Override
24604        public List<PackageInfo> getOverlayPackages(int userId) {
24605            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
24606            synchronized (mPackages) {
24607                for (PackageParser.Package p : mPackages.values()) {
24608                    if (p.mOverlayTarget != null) {
24609                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
24610                        if (pkg != null) {
24611                            overlayPackages.add(pkg);
24612                        }
24613                    }
24614                }
24615            }
24616            return overlayPackages;
24617        }
24618
24619        @Override
24620        public List<String> getTargetPackageNames(int userId) {
24621            List<String> targetPackages = new ArrayList<>();
24622            synchronized (mPackages) {
24623                for (PackageParser.Package p : mPackages.values()) {
24624                    if (p.mOverlayTarget == null) {
24625                        targetPackages.add(p.packageName);
24626                    }
24627                }
24628            }
24629            return targetPackages;
24630        }
24631
24632        @Override
24633        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
24634                @Nullable List<String> overlayPackageNames) {
24635            synchronized (mPackages) {
24636                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
24637                    Slog.e(TAG, "failed to find package " + targetPackageName);
24638                    return false;
24639                }
24640                ArrayList<String> overlayPaths = null;
24641                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
24642                    final int N = overlayPackageNames.size();
24643                    overlayPaths = new ArrayList<>(N);
24644                    for (int i = 0; i < N; i++) {
24645                        final String packageName = overlayPackageNames.get(i);
24646                        final PackageParser.Package pkg = mPackages.get(packageName);
24647                        if (pkg == null) {
24648                            Slog.e(TAG, "failed to find package " + packageName);
24649                            return false;
24650                        }
24651                        overlayPaths.add(pkg.baseCodePath);
24652                    }
24653                }
24654
24655                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
24656                ps.setOverlayPaths(overlayPaths, userId);
24657                return true;
24658            }
24659        }
24660
24661        @Override
24662        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
24663                int flags, int userId) {
24664            return resolveIntentInternal(
24665                    intent, resolvedType, flags, userId, true /*resolveForStart*/);
24666        }
24667
24668        @Override
24669        public ResolveInfo resolveService(Intent intent, String resolvedType,
24670                int flags, int userId, int callingUid) {
24671            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
24672        }
24673
24674        @Override
24675        public void addIsolatedUid(int isolatedUid, int ownerUid) {
24676            synchronized (mPackages) {
24677                mIsolatedOwners.put(isolatedUid, ownerUid);
24678            }
24679        }
24680
24681        @Override
24682        public void removeIsolatedUid(int isolatedUid) {
24683            synchronized (mPackages) {
24684                mIsolatedOwners.delete(isolatedUid);
24685            }
24686        }
24687
24688        @Override
24689        public int getUidTargetSdkVersion(int uid) {
24690            synchronized (mPackages) {
24691                return getUidTargetSdkVersionLockedLPr(uid);
24692            }
24693        }
24694
24695        @Override
24696        public boolean canAccessInstantApps(int callingUid, int userId) {
24697            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
24698        }
24699    }
24700
24701    @Override
24702    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
24703        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
24704        synchronized (mPackages) {
24705            final long identity = Binder.clearCallingIdentity();
24706            try {
24707                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
24708                        packageNames, userId);
24709            } finally {
24710                Binder.restoreCallingIdentity(identity);
24711            }
24712        }
24713    }
24714
24715    @Override
24716    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
24717        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
24718        synchronized (mPackages) {
24719            final long identity = Binder.clearCallingIdentity();
24720            try {
24721                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr(
24722                        packageNames, userId);
24723            } finally {
24724                Binder.restoreCallingIdentity(identity);
24725            }
24726        }
24727    }
24728
24729    private static void enforceSystemOrPhoneCaller(String tag) {
24730        int callingUid = Binder.getCallingUid();
24731        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
24732            throw new SecurityException(
24733                    "Cannot call " + tag + " from UID " + callingUid);
24734        }
24735    }
24736
24737    boolean isHistoricalPackageUsageAvailable() {
24738        return mPackageUsage.isHistoricalPackageUsageAvailable();
24739    }
24740
24741    /**
24742     * Return a <b>copy</b> of the collection of packages known to the package manager.
24743     * @return A copy of the values of mPackages.
24744     */
24745    Collection<PackageParser.Package> getPackages() {
24746        synchronized (mPackages) {
24747            return new ArrayList<>(mPackages.values());
24748        }
24749    }
24750
24751    /**
24752     * Logs process start information (including base APK hash) to the security log.
24753     * @hide
24754     */
24755    @Override
24756    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
24757            String apkFile, int pid) {
24758        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24759            return;
24760        }
24761        if (!SecurityLog.isLoggingEnabled()) {
24762            return;
24763        }
24764        Bundle data = new Bundle();
24765        data.putLong("startTimestamp", System.currentTimeMillis());
24766        data.putString("processName", processName);
24767        data.putInt("uid", uid);
24768        data.putString("seinfo", seinfo);
24769        data.putString("apkFile", apkFile);
24770        data.putInt("pid", pid);
24771        Message msg = mProcessLoggingHandler.obtainMessage(
24772                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
24773        msg.setData(data);
24774        mProcessLoggingHandler.sendMessage(msg);
24775    }
24776
24777    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
24778        return mCompilerStats.getPackageStats(pkgName);
24779    }
24780
24781    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
24782        return getOrCreateCompilerPackageStats(pkg.packageName);
24783    }
24784
24785    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
24786        return mCompilerStats.getOrCreatePackageStats(pkgName);
24787    }
24788
24789    public void deleteCompilerPackageStats(String pkgName) {
24790        mCompilerStats.deletePackageStats(pkgName);
24791    }
24792
24793    @Override
24794    public int getInstallReason(String packageName, int userId) {
24795        final int callingUid = Binder.getCallingUid();
24796        enforceCrossUserPermission(callingUid, userId,
24797                true /* requireFullPermission */, false /* checkShell */,
24798                "get install reason");
24799        synchronized (mPackages) {
24800            final PackageSetting ps = mSettings.mPackages.get(packageName);
24801            if (filterAppAccessLPr(ps, callingUid, userId)) {
24802                return PackageManager.INSTALL_REASON_UNKNOWN;
24803            }
24804            if (ps != null) {
24805                return ps.getInstallReason(userId);
24806            }
24807        }
24808        return PackageManager.INSTALL_REASON_UNKNOWN;
24809    }
24810
24811    @Override
24812    public boolean canRequestPackageInstalls(String packageName, int userId) {
24813        return canRequestPackageInstallsInternal(packageName, 0, userId,
24814                true /* throwIfPermNotDeclared*/);
24815    }
24816
24817    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
24818            boolean throwIfPermNotDeclared) {
24819        int callingUid = Binder.getCallingUid();
24820        int uid = getPackageUid(packageName, 0, userId);
24821        if (callingUid != uid && callingUid != Process.ROOT_UID
24822                && callingUid != Process.SYSTEM_UID) {
24823            throw new SecurityException(
24824                    "Caller uid " + callingUid + " does not own package " + packageName);
24825        }
24826        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
24827        if (info == null) {
24828            return false;
24829        }
24830        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
24831            return false;
24832        }
24833        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
24834        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
24835        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
24836            if (throwIfPermNotDeclared) {
24837                throw new SecurityException("Need to declare " + appOpPermission
24838                        + " to call this api");
24839            } else {
24840                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
24841                return false;
24842            }
24843        }
24844        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
24845            return false;
24846        }
24847        if (mExternalSourcesPolicy != null) {
24848            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
24849            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
24850                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
24851            }
24852        }
24853        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
24854    }
24855
24856    @Override
24857    public ComponentName getInstantAppResolverSettingsComponent() {
24858        return mInstantAppResolverSettingsComponent;
24859    }
24860
24861    @Override
24862    public ComponentName getInstantAppInstallerComponent() {
24863        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24864            return null;
24865        }
24866        return mInstantAppInstallerActivity == null
24867                ? null : mInstantAppInstallerActivity.getComponentName();
24868    }
24869
24870    @Override
24871    public String getInstantAppAndroidId(String packageName, int userId) {
24872        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
24873                "getInstantAppAndroidId");
24874        enforceCrossUserPermission(Binder.getCallingUid(), userId,
24875                true /* requireFullPermission */, false /* checkShell */,
24876                "getInstantAppAndroidId");
24877        // Make sure the target is an Instant App.
24878        if (!isInstantApp(packageName, userId)) {
24879            return null;
24880        }
24881        synchronized (mPackages) {
24882            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
24883        }
24884    }
24885
24886    boolean canHaveOatDir(String packageName) {
24887        synchronized (mPackages) {
24888            PackageParser.Package p = mPackages.get(packageName);
24889            if (p == null) {
24890                return false;
24891            }
24892            return p.canHaveOatDir();
24893        }
24894    }
24895
24896    private String getOatDir(PackageParser.Package pkg) {
24897        if (!pkg.canHaveOatDir()) {
24898            return null;
24899        }
24900        File codePath = new File(pkg.codePath);
24901        if (codePath.isDirectory()) {
24902            return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath();
24903        }
24904        return null;
24905    }
24906
24907    void deleteOatArtifactsOfPackage(String packageName) {
24908        final String[] instructionSets;
24909        final List<String> codePaths;
24910        final String oatDir;
24911        final PackageParser.Package pkg;
24912        synchronized (mPackages) {
24913            pkg = mPackages.get(packageName);
24914        }
24915        instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
24916        codePaths = pkg.getAllCodePaths();
24917        oatDir = getOatDir(pkg);
24918
24919        for (String codePath : codePaths) {
24920            for (String isa : instructionSets) {
24921                try {
24922                    mInstaller.deleteOdex(codePath, isa, oatDir);
24923                } catch (InstallerException e) {
24924                    Log.e(TAG, "Failed deleting oat files for " + codePath, e);
24925                }
24926            }
24927        }
24928    }
24929}
24930
24931interface PackageSender {
24932    void sendPackageBroadcast(final String action, final String pkg,
24933        final Bundle extras, final int flags, final String targetPkg,
24934        final IIntentReceiver finishedReceiver, final int[] userIds);
24935    void sendPackageAddedForNewUsers(String packageName, boolean isSystem,
24936        int appId, int... userIds);
24937}
24938